distinct用于返回唯一不同的值。
表table1:
id | value |
1 | a |
1 | a |
2 | b |
3 | b |
4 | c |
5 | c |
表table2:
username | password |
tom | s123456 |
toms | 123456 |
表table3:
username | phone |
tom | 10086 |
jack | 10010 |
作用于单列
select distinct value from table1
执行结果如下:
value |
a |
b |
c |
作用于多列
例1:
select distinct id, name from table1
执行结果如下:
id | value |
1 | a |
2 | b |
3 | b |
4 | c |
5 | c |
通过这个例子可以看出,多列去重是根据写在distinct后面的各个字段来去重的(当这几个字段所有的列的值都相同时才会被认为是重复数据)。
例2:
select distinct username, password from table2
执行结果如下:
username | password |
tom | s123456 |
toms | 123456 |
执行结果为两行,这说明distinct是分别作用了username和password列,而不是把这两列的值“拼接”后再去重的。
多表查询
select distinct o.username from table2 o , table3 t where o.username = t.username ;
执行结果如下:
username |
tom |
此外还需要注意一下几点:
1.distinct必须放在开头,如果不放在开头会报错
select id, distinct value from table1; --会提示错误
2.多表查询时,如果表中有相同字段名,需指定是那张表的字段
select distinct username from table2 o , table3 t where o.username = t.username ; --会提示错误
3.COUNT统计单字段
select count(distinct value) from table1; --表中value去重后的数目
4.COUNT统计多字段
count是不能统计多个字段的,可以使用嵌套查询解决:
select count(*) from (select distinct username, password from table2) as t2;
如果这样查询:select count(distinct value, id) from table1;会报错
5.显示字段
显示的字段只能是distinct指定的字段