mysql中select distinct的用法
来源:互联网 发布:淘宝男皮鞋 编辑:程序博客网 时间:2024/05/19 20:00
在使用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
举例如下:
这是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
1 0
- mysql中select distinct的用法
- mysql 去除重复 Select中DISTINCT关键字的用法
- Select中DISTINCT关键字的用法——mysql
- mysql 去除重复 Select中DISTINCT关键字的用法
- mysql 去除重复 Select中DISTINCT关键字的用法
- mysql 去除重复 Select中DISTINCT关键字的用法
- mysql 去除重复 Select中DISTINCT关键字的用法
- Select中DISTINCT关键字的用法
- Select中DISTINCT关键字的用法?
- Select中DISTINCT关键字的用法
- Select中DISTINCT关键字的用法?
- Select中DISTINCT关键字的用法
- Select中DISTINCT关键字的用法
- MySql中distinct的用法
- MySql中distinct的用法
- MySql中distinct的用法
- mysql中distinct的用法
- MySQL 中 distinct 的用法
- Hardware-javaaplication.
- Android ViewGroup点击效果(背景色)
- noip1996 乘法运算 - 普及组 (模拟)
- POJ3667-Hotel-线段树区间合并(模板)
- 南邮 OJ 1584 连通 OR 不连通
- mysql中select distinct的用法
- iOS开发:开发中如何更改项目名
- MS SQL Server之光标、存储过程和触发器
- c++中的map用法详解
- 悬崖勒马之三年编码的反省
- C语言字符串处理函数
- opencv学习(六)书本《学习Opencv》(中文版)第四章的作业答案第二题(opencv3.0.0+VS2012+win7)
- android实现类似toast效果的圆角dialog警告框
- tmux(终端方便使用cp:http://wowubuntu.com/tmux.html)