GROUP BY 子句在不使用聚合函数的情况下将如何执行?
如果我们在 SELECT 语句中使用 GROUP BY 子句而不使用聚合函数,它将表现得像 DISTINCT 子句。例如,我们有以下表格 -
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)
通过对列‘Address’使用 DISTINCT 子句,MySQL 返回以下结果集。
mysql> Select DISTINCT ADDRESS from Student_info; +------------+ | ADDRESS | +------------+ | Amritsar | | Chandigarh | | Shimla | | Jhansi | | Delhi | | NULL | +------------+ 6 rows in set (0.07 sec)
现在,通过如下使用 GROUP BY 子句,我们可以得到与使用 DISTINCT 得到的相同结果集 -
mysql> Select ADDRESS from Student_info GROUP BY Address; +------------+ | ADDRESS | +------------+ | NULL | | Amritsar | | Chandigarh | | Delhi | | Jhansi | | Shimla | +------------+ 6 rows in set (0.00 sec)
我们可以观察到 MySQL 根据 GROUP BY 子句返回的结果集是有序的,而根据 DISTICT 子句返回的结果集是无序的。
广告