group by与distinct的区别介绍
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如果索引建的 恰当的话,会有性能上的提高。