是的,可以使用MySQL的GROUP BY子句來將多個欄位分組,就像我們可以使用MySQL的DISTINCT子句一樣。考慮以下範例,在第一個查詢中我們使用了DISTINCT子句,在名為‘testing’的表的‘fname’和‘Lname’欄位上使用了GROUP BY子句的第二個查詢。
mysql> Select * from testing; +------+---------+---------+ | id | fname | Lname | +------+---------+---------+ | 200 | Raman | Kumar | | 201 | Sahil | Bhalla | | 202 | Gaurav | NULL | | 203 | Aarav | NULL | | 204 | Harshit | Khurana | | 205 | Rahul | NULL | | 206 | Piyush | Kohli | | 207 | Lovkesh | NULL | | 208 | Gaurav | Kumar | | 209 | Raman | Kumar | +------+---------+---------+ 10 rows in set (0.00 sec) mysql> Select DISTINCT FNAME,LNAME from testing; +---------+---------+ | FNAME | LNAME | +---------+---------+ | Raman | Kumar | | Sahil | Bhalla | | Gaurav | NULL | | Aarav | NULL | | Harshit | Khurana | | Rahul | NULL | | Piyush | Kohli | | Lovkesh | NULL | | Gaurav | Kumar | +---------+---------+ 9 rows in set (0.00 sec) mysql> Select Fname, LNAME from testing GROUP BY Fname,Lname; +---------+---------+ | Fname | LNAME | +---------+---------+ | Aarav | NULL | | Gaurav | NULL | | Gaurav | Kumar | | Harshit | Khurana | | Lovkesh | NULL | | Piyush | Kohli | | Rahul | NULL | | Raman | Kumar | | Sahil | Bhalla | +---------+---------+ 9 rows in set (0.00 sec)
唯一的差異是,使用GROUP BY子句的MySQL查詢傳回的結果集是排序的,而使用DISTINCT子句的MySQL查詢傳回的結果集則沒有排序。
以上是我們可以像使用 MySQL DISTINCT 子句一樣對多個欄位使用 MySQL GROUP BY 子句嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!