1 Fork me on GitHub

23. SQL--distinct关键字:删除重复记录

1. 前言

sql distinct 关键字需要和 select 语句一起使用,用来删除结果集中所有重复的记录,仅保留唯一的一条记录。

数据表中有时候会有重复的记录,如果您只需要其中一条,就可以使用 distinct 关键字。
关于 unique 关键字
unique 和 distinct 的效果是等价的,都用来消除结果集中的重复记录,但是 unique 是一种老式的语法,oracle 数据库曾经使用过。

后来 ansi(美国国家标准委局)将 distinct 定义为正式的关键字,oracle 也随即增加了对 distinct 的支持;但是为了保持向后兼容,oracle 并没有取消 unique 关键字。

2. 语法

distinct 关键字的基本语法格式如下:

select distinct column1, column2,.....columnn
from table_name
where [condition]

3. 示例

现在有包含如下记录的 website 表:

+----+----------------+----------------------------+-----+-------+---------+---------+
| id | name           | url                        | age | alexa | uv      | country |
+----+----------------+----------------------------+-----+-------+---------+---------+
|  1 | 百度           | https://www.baidu.com/     |  20 |     4 |  5010.5 | CN      |
|  2 | 淘宝           | https://www.taobao.com/    |  20 |     8 | 3996.75 | CN      |
|  3 | C语言中文网    | http://c.biancheng.net/    |  12 |  7923 |   11.62 | CN      |
|  4 | Google         | https://www.google.com/    |  23 |     1 |   36474 | US      |
|  5 | GitHub         | https://github.com/        |  15 |    95 |   216.3 | US      |
|  6 | Stack Overflow | https://stackoverflow.com/ |  15 |    48 |   592.2 | US      |
|  7 | Yandex         | http://www.yandex.ru/      |  11 |    53 |  591.82 | RU      |
|  8 | VK             | https://vk.com/            |  23 |    23 |    1206 | RU      |
+----+----------------+----------------------------+-----+-------+---------+---------+

下面的 SELECT 语法返回的记录中包含了重复的 age 和 country:

select age, country from website
order by age;

执行结果:

+-----+---------+
| age | country |
+-----+---------+
|  11 | RU      |
|  12 | CN      |
|  15 | US      |
|  15 | US      |
|  20 | CN      |
|  20 | CN      |
|  23 | US      |
|  23 | RU      |
+-----+---------+

可以看到,age=15 和 country=us、age=20 和 country=cn 都重复出现了两次,这是因为原始表中就包含重复的记录。

现在,我们在 select 语句中加入 distinct 关键字,去除重复的记录:

select distinct age, country from website
order by age;

执行结果:

+-----+---------+
| age | country |
+-----+---------+
|  11 | RU      |
|  12 | CN      |
|  15 | US      |
|  20 | CN      |
|  23 | RU      |
|  23 | US      |
+-----+---------+

可以看到,age=15 和 country=US、age=20 和 country=CN 都只出现了一次,重复记录被去除。

posted @ 2022-08-31 09:15  v_jjling  阅读(473)  评论(0)    收藏  举报
AmazingCounters.com