当前位置 - 股票行情交易網 - 財經新聞 - group by與distinct有何區別

group by與distinct有何區別

他們的功能基本上是不壹樣的。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如果索引建的恰當的話,會有性能上的提高。