Home  >  Article  >  Database  >  mysql中selectdistinct的用法_MySQL

mysql中selectdistinct的用法_MySQL

WBOY
WBOYOriginal
2016-06-01 12:58:451019browse

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

举例如下:
这是test表的结构
id test1 test2
1 a 1
2 a 2
3 a 3
4 a 1
5 b 1
6 b 2
7 b 3
8 b 2
比如我想用一条语句查询得到test1不重复的所有数据,那就必须使用distinct去掉多余的重复记录。
select distinct test1 from test
得到的结果是:
test1
a
b
好像达到效果了,可是,我想要得到的是id值?改一下查询语句吧:
select distinct test1, id from test


test1 id
a 1
a 2
a 3
a 4
b 5
b 6
b 7
b 8
distinct怎么没起作用?作用是起了的,不过他同时作用了两个字段,也就是必须得id与test1都相同的才会被排除,这不可能的,id是自动增长的。。。

我们再改改查询语句:

select id, distinct test1 from test
很遗憾,除了错误信息你什么也得不到,distinct必须放在开头。难到不能把distinct放到where条件里?能,照样报错。。。。。。。

通过查阅手册,可以通过group_cancat来实现:
SELECT id, group_concat( DISTINCT test1 ) FROM test GROUP BY test1
id group_concat( distinct test1 )
1 a
5 b
不过它只有在4.1.0以后才能用,对于那些老版本的数据库是不行的。


可以通过其他函数来实现:
select *, count(distinct test1) from test group by test1
id test1 test2 count( distinct test1 )
1 a 1 1
5 b 1 1
最后一项是多余的,不用管就行了,目的达到。。。。。

还有更简单的方法也可以实现:
select id, test1 from test group by test1
id test1
1 a
5 b

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn