MySQL中distinct的使用方法
2017-06-22 23:13
579 查看
本文的环境是Windows 10,MySQL版本是5.7.12-log
这里的expressions可以是多个字段。本文的所有操作都是针对如下示例表的:
![](https://oscdn.geek-share.com/Uploads/Images/Content/201706/c8d199492f9c7e0360a46ba6d8f0fef7)
结果如下:
![](https://oscdn.geek-share.com/Uploads/Images/Content/201706/a692848d1d4e87c69caadd2f20a5fc11)
结果如下:
![](https://oscdn.geek-share.com/Uploads/Images/Content/201706/066c4f6f06f7470d8f6dafb66b783dde)
从上例中可以发现,当
抛出错误如下:
[Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘DISTINCT province from person’ at line 1
1.3 针对
从1.1和1.2中都可以看出,
1.4 与
默认情况下,查询时返回所有的结果,此时使用的就是
结果如下:
![](https://oscdn.geek-share.com/Uploads/Images/Content/201706/4f43d76c27f59a47f3227496f26fcb69)
1.5 与
这个语句与distinct的作用是相同的。
1.6 对
相当于
一、基本使用
distinct一般是用来去除查询结果中的重复记录的,而且这个语句在
select、
insert、
delete和
update中只可以在
select中使用,具体的语法如下:
select distinct expression[,expression...] from tables [where conditions];
这里的expressions可以是多个字段。本文的所有操作都是针对如下示例表的:
CREATE TABLE `NewTable` ( `id` int(11) NOT NULL AUTO_INCREMENT , `name` varchar(30) NULL DEFAULT NULL , `country` varchar(50) NULL DEFAULT NULL , `province` varchar(30) NULL DEFAULT NULL , `city` varchar(30) NULL DEFAULT NULL , PRIMARY KEY (`id`) )ENGINE=InnoDB ;
1.1 只对一列操作
这种操作是最常见和简单的,如下:select distinct country from person
结果如下:
1.2 对多列进行操作
select distinct country, province from person
结果如下:
从上例中可以发现,当
distinct应用到多个字段的时候,其应用的范围是其后面的所有字段,而不只是紧挨着它的一个字段,而且
distinct只能放到所有字段的前面,如下语句是错误的:
SELECT country, distinct province from person; // 该语句是错误的
抛出错误如下:
[Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘DISTINCT province from person’ at line 1
1.3 针对NULL
的处理
从1.1和1.2中都可以看出,distinct对
NULL是不进行过滤的,即返回的结果中是包含
NULL值的。
1.4 与ALL
不能同时使用
默认情况下,查询时返回所有的结果,此时使用的就是all语句,这是与
distinct相对应的,如下:
select all country, province from person
结果如下:
1.5 与distinctrow
同义
select distinctrow expression[,expression...] from tables [where conditions];
这个语句与distinct的作用是相同的。
1.6 对*
的处理
*代表整列,使用distinct对
*操作
sql select DISTINCT * from person
相当于
select DISTINCT id, `name`, country, province, city from person;
相关文章推荐
- Mysql中count(*),DISTINCT的使用方法和效率研究
- Mysql中count(*),DISTINCT的使用方法和效率研究
- Mysql中count(*),DISTINCT的使用方法和效率研究
- MySQL中distinct和count(*)的使用方法比较
- Mysql中count(*),DISTINCT的使用方法和效率研究
- Mysql中count(*),DISTINCT的使用方法和效率研究
- Mysql中count(*),DISTINCT的使用方法和效率研究
- Mysql中count(*),DISTINCT的使用方法和效率研究
- Mysql中count(*),DISTINCT的使用方法和效率研究
- Mysql中count(*),DISTINCT的使用方法和效率研究
- mysql中count(*),distinct的使用方法和效率研究
- Mysql中count(*),DISTINCT的使用方法和效率研究
- MySQL中distinct和count(*)的使用方法比较
- Mysql中count(*),DISTINCT的使用方法和效率研究
- Mysql中count(*),DISTINCT的使用方法和效率研究
- Mysql中count(*),DISTINCT的使用方法和效率研究
- Mysql中count(*),DISTINCT的使用方法和效率研究
- mysql中select distinct的使用方法
- Mysql中count(*),DISTINCT的使用方法和效率研究
- mysql中count(*),distinct的使用方法和效率研究