group by與distinct有何區別
阿新 • • 發佈:2019-02-03
他們的功能基本上是不一樣的。 distinct消除重複行。 group by是分組語句。 舉例來說可能方便一點。 A表id numa 1b 2c 3a 4c 7d 3e 5 如果只選出id列,用distinct和group by 一樣的。 select distinct(id) from A;idabcde;select id from A group by id;idabcde;不同之處可能在於group by有排序功能。 但是如果需要加上另一列num,結果不同。 group by 是分組語句,如果用 select id,num from A group by id,num; 這樣的結果在本例中與不加group by是一樣的,因為num各個不同。 但是如果select id,num from A group by id; 注意該語句是錯誤語句,因為num沒有使用聚組函式,例如:sum(求和),avg(求平均數) select id,sum(num) from A group by id; id sum(num)a 5b 2c 10d 3e 5 用distinct不顯示重複的行。 在本例中select distinct id,num from A;的結果也和不加distinct一致。 因為id,num沒有重複的行,而不是隻看id。 group by 功能更強大一些,另外推薦使用group by。 因為distinct會導致全表掃描,而group by如果索引建的 恰當的話,會有效能上的提高。
轉載自:http://zhidao.baidu.com/link?url=zNRLuAZ7vM40YSFfeKJD4JYhmzHgQxd5m9GjEbnMXPlzTOTCAqXxHiZPxQv6qjMSgk4qduY4zjPzvQTsGdTOZPns14oAz7tuGiuiBxfALRW
另參考:http://liubin2010.iteye.com/blog/1130415