`

group by与distinct的区别

    博客分类:
  • DB
 
阅读更多

举例来说可能方便一点。 
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如果索引建的 
恰当的话,会有性能上的提高。

 

 SELECT DISTINCT user_id
FROM TRANSACTIONS


SELECT  user_id,COUNT(*) AS num
FROM TRANSACTIONS
GROUP BY  user_id
 

 

------------

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics