当前位置:Gxlcms > 数据库问题 > mysql中select distinct的使用方法

mysql中select distinct的使用方法

时间:2021-07-01 10:21:17 帮助过:25人阅读

比方我想用一条语句查询得到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

mysql中select distinct的使用方法

标签:错误   其他   mil   过滤   art   数据库   its   版本号   错误信息   

人气教程排行