SQL DINTINCT
select distinct
语句用于返回唯一不同的值。
表 \(a\):
id | name |
---|---|
1 | a |
2 | b |
3 | c |
4 | c |
5 | b |
1 | a |
表 \(b\):
姓 | 名 |
---|---|
wang | ke |
wangk | e |
1. 作用于单列
select distinct name from a
name |
---|
a |
b |
c |
2. 作用于多列
select distinct name, id from a
name | id |
---|---|
a | 1 |
b | 2 |
c | 3 |
c | 4 |
b | 5 |
根据 \(name,id\) 两个字段来去重,这种方式 \(Access、SQL\ Server\) 都支持。
select distinct 姓, 名 from b;
姓 | 名 |
---|---|
wang | ke |
wangk | e |
distinct
并非对姓、名两列字符串拼接后再去重,而是分别作用于姓、名两列。
3. count 统计
select count(distinct name) from a; -- a表中name去重后的数目,SQL Server支持,而Access不支持
count(distinct name) |
---|
3 |
count
不能统计多个字段。
select count(name, id) from a;
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 ', id) from a' at line 1
select count(distinct name, id) from a;
count(distinct name, id) |
---|
5 |
嵌套查询。
select count(*) from (select distinct 姓, 名 from B) AS M;
count(*) |
---|
2 |
4. distinct 必须放在开头
select id, distinct name from a; --会提示错误,因为distinct必须放在开头
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 name from a' at line 1
来自:Rain Man