摘要:在本教程中,您將學習如何使用 SQL DISTINCT 運算子從表中選擇不重複的值。
SQL DISTINCT 運算子簡介 #
要從表的某一列中選擇不重複的值,您可以在 SELECT 子句中使用 DISTINCT 運算子,如下所示:
SELECT DISTINCT
column1
FROM
table_name;Code language: SQL (Structured Query Language) (sql)在此語法中,SELECT 語句返回一個結果集,其中包含表中 column1 列的唯一值。
SQL 允許您將多個列與 DISTINCT 運算子一起使用:
SELECT DISTINCT
column1,
column2
FROM
table_name;在這種情況下,SELECT 語句會使用 column1 和 column2 兩列的值組合來評估行的唯一性,並將不重複的行包含在結果集中。
請注意,DISTINCT 僅從表中選擇不重複的值,它不會刪除表中的重複行。
如果您想選擇兩列並移除其中一列的重複項,您應該改用 GROUP BY 子句。
SQL DISTINCT 運算子示例 #
我們將使用示例資料庫中的 employees 表來演示 DISTINCT 運算子的工作原理。

從單列中選擇不重複行的示例 #
以下語句從 employees 表的 salary 列中檢索資料,並按從高到低的順序排序:
SELECT
salary
FROM
employees
ORDER BY
salary DESC;Code language: SQL (Structured Query Language) (sql)+----------+
| salary |
+----------+
| 24000.00 |
| 17000.00 |
| 17000.00 |
| 14000.00 |
| 13500.00 |
| 13000.00 |
| 12000.00 |
| 12000.00 |
| 11000.00 |
| 10000.00 |
| 9000.00 |
| 9000.00 |
...結果集有一些重複項,例如 17000、12000 和 9000。
以下語句使用 DISTINCT 運算子從 employees 表的 salary 列中選擇唯一值:
SELECT DISTINCT
salary
FROM
employees
ORDER BY
salary DESC;Code language: SQL (Structured Query Language) (sql) salary
----------
24000.00
17000.00
14000.00
13500.00
13000.00
12000.00
11000.00
10000.00
9000.00
...Code language: plaintext (plaintext)輸出顯示 DISTINCT 運算子返回了唯一的薪資金額。
在多列上選擇不重複行的示例 #
以下語句從 employees 表中檢索職位 ID 和薪水:
SELECT
job_id,
salary
FROM
employees
ORDER BY
job_id,
salary DESC;Code language: SQL (Structured Query Language) (sql) job_id | salary
--------+----------
1 | 8300.00
2 | 12000.00
3 | 4400.00
4 | 24000.00
5 | 17000.00
5 | 17000.00
6 | 9000.00
6 | 8200.00
6 | 7800.00
6 | 7700.00
6 | 6900.00
7 | 12000.00
...Code language: plaintext (plaintext)結果集有一些重複行,例如職位 ID 為 5,薪水為 17000。這意味著有兩名員工具有相同的職位 ID 和薪水。
以下語句使用 DISTINCT 運算子來移除職位 ID 和薪水中的重複值:
SELECT DISTINCT
job_id,
salary
FROM
employees
ORDER BY
job_id,
salary DESC;Code language: SQL (Structured Query Language) (sql) job_id | salary
--------+----------
1 | 8300.00
2 | 12000.00
3 | 4400.00
4 | 24000.00
5 | 17000.00
6 | 9000.00
6 | 8200.00
6 | 7800.00
...Code language: plaintext (plaintext)請注意,您在 job_id 列中仍然會看到重複值,因為 DISTINCT 運算子是使用 job_id 和 salary 兩列的值來評估重複性,而不僅僅是 job_id 列中的值。
SQL DISTINCT 與 NULL #
在資料庫世界中,NULL 是一個特殊的值,代表未知或缺失的資料。
與常規值不同,NULL 不等於任何東西,甚至不等於它自己。例如,以下表達式將產生 NULL,即未知:
SELECT
NULL = NULL;Code language: PHP (php)通常,DISTINCT 運算子將所有 NULL 值視為相同。因此,DISTINCT 運算子在結果集中只保留一個 NULL。
請注意,這種行為在不同的資料庫產品之間可能會有所不同。
例如,以下語句返回員工的不重複電話號碼:
SELECT DISTINCT
phone_number
FROM
employees
ORDER BY
phone_number DESC;Code language: SQL (Structured Query Language) (sql) phone_number
--------------
NULL
650.501.2876
650.501.1876
650.124.1224
650.123.4234
...Code language: plaintext (plaintext)請注意,查詢在結果集中只返回一個 NULL。
摘要 #
- 在
SELECT子句中使用DISTINCT運算子,可以從表的一個或多個列中選擇唯一值。
資料庫 #
- PostgreSQL DISTINCT 運算子
- Oracle DISTINCT 運算子
- SQL Server DISTINCT 運算子
- MySQL DISTINCT 運算子
- SQLite DISTINCT 運算子
- Db2 DISTINCT 運算子
- MariaDB DISTINCT 運算子