您的位置:首页 > 数据库 > MySQL

mysql中select distinct的使用方法

2017-04-29 12:55 369 查看
在使用mysql时,有时须要查询出某个字段不反复的记录,尽管mysql提供有distinct这个keyword来过滤掉多余的反复记录仅仅保留一条,但往往仅仅用它来返回不反复记录的条数,而不是用它来返回不重记录的全部值。其原因是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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: