Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

GROUP BY hoạt động như thế nào khi không có hàm tổng hợp?

Khi dùng GROUP BY trong SELECT không dùng hàm tổng hợp, nó hoạt động như DISTINCT. Ví dụ bảng Student_info:

mysql> Select * from Student_info;
+------+---------+------------+------------+
| id   | Name    | Address    | Subject    |
+------+---------+------------+------------+
| 101  | YashPal | Amritsar   | History    |
| 105  | Gaurav  | Chandigarh | Literature |
| 125  | Raman   | Shimla     | Computers  |
| 130  | Ram     | Jhansi     | Computers  |
| 132  | Shyam   | Chandigarh | Economics  |
| 133  | Mohan   | Delhi      | Computers  |
| 150  | Saurabh | NULL       | Literature |
+------+---------+------------+------------+
7 rows in set (0.00 sec)

Dùng DISTINCT trên Address:

mysql> Select DISTINCT ADDRESS from Student_info;
+------------+
| ADDRESS    |
+------------+
| Amritsar   |
| Chandigarh |
| Shimla     |
| Jhansi     |
| Delhi      |
| NULL       |
+------------+
6 rows in set (0.07 sec)

Dùng GROUP BY cho cùng kết quả:

mysql> Select ADDRESS from Student_info GROUP BY Address;
+------------+
| ADDRESS    |
+------------+
| NULL       |
| Amritsar   |
| Chandigarh |
| Delhi      |
| Jhansi     |
| Shimla     |
+------------+
6 rows in set (0.00 sec)

Khác biệt: GROUP BY trả về đã sắp xếp, DISTINCT không sắp xếp.