select distinct a from tbl = select a from tbl group by a
他們的功能基本上是不一樣的。
distinct消除重複行。
group by是分組語句。
舉例來說可能方便一點。
A表
id num
a 1
b 2
c 3
a 4
c 7
d 3
e 5
如果只選出id列,用distinct和group by 一樣的。
select distinct(id) from A;
id
a
b
c
d
e;
select id from A group by id;
id
a
b
c
d
e;
不同之處可能在於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 5
b 2
c 10
d 3
e 5
用distinct不顯示重複的行。
在本例中
select distinct id,num from A;的結果也和不加distinct一致。
因爲id,num沒有重複的行,而不是隻看id。
group by 功能更強大一些,另外推薦使用group by。
因爲distinct會導致全表掃描,而group by如果索引建的
恰當的話,會有性能上的提高。