`
zhengdl126
  • 浏览: 2513228 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类

mysql的distinct用法

阅读更多

使用mysql时,有时需要查询出某个字段不重复的记录,虽然mysql提供有 distinct这个关键字来过滤掉多余的重复记录只保留一条,但往往只用它来返回不重复记录的条数,而不是用它来返回不重记录的所有值。其原因是 distinct只能返回它的目标字段,而无法返回其它字段

下面先来看看例子:

   table
   id name
   1 a
   2 b
   3 c
   4 c
   5 b

比如我想用一条语句查询得到name不重复的所有数据,那就必须使用distinct去掉多余的重复记录。

select distinct name from table
得到的结果是:

   name
   a
   b
   c

好像达到效果了,可是,我想要得到的是id值呢?改一下查询语句吧:

select distinct name, id from table

结果会是:

   id name
   1 a
   2 b
   3 c
   4 c
   5 b

 

试了半天,也不行,最后在mysql手册里找到一个用法,

用group_concat(distinct name)配合group by name实现了我所需要的功能 5.0才支持的.

 

突然灵机一闪,既然可以使用group_concat函数,那其它函数能行吗?

赶紧用count函数一试,成功, 现在将完整语句放出:

select *, count(distinct name) from table group by name

结果:

   id name count(distinct name)
   1 a 1
   2 b 1
   3 c 1

再顺便说一句,group by 必须放在 order by 和 limit之前, 不然会报错。。。OK了

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics