摘要: 在本教學中,您將學習如何使用 SQL DISTINCT
運算子從結果集中移除重複項
SQL DISTINCT 運算子簡介
若要從結果集中移除重複的列,您可以在 SELECT
子句中使用 DISTINCT
運算子,如下所示
SELECT DISTINCT
column1, column2, ...
FROM
table1;
Code language: SQL (Structured Query Language) (sql)
如果在 DISTINCT
運算子後使用一個欄位,DISTINCT
運算子會使用該欄位中的值來評估重複項。
如果您使用兩個或多個欄位,DISTINCT
將使用這些欄位中值的組合來評估重複項。
請注意,DISTINCT
僅從結果集中移除重複的列。它不會刪除表格中的重複列。
如果您想要選擇兩個欄位並移除其中一個欄位中的重複項,您應該改用 GROUP BY
子句。
SQL DISTINCT 範例
我們將使用範例資料庫中的 employees
表格來示範 DISTINCT
運算子的運作方式。

1) 在一個欄位上使用 SQL 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)
如您所見,結果集不包含任何重複的薪資值。
2) 在多個欄位上使用 SQL DISTINCT 運算子的範例
以下語句從 employees
表格中選擇 job id 和 salary
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 |
...
Code language: plaintext (plaintext)
結果集有一些重複的列,例如 job id 5 salary 17000。這表示有兩位員工具有相同的 job id 和 salary。
以下語句使用 DISTINCT
運算子移除 job id 和 salary 中的重複值
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 |
...
Code language: plaintext (plaintext)
請注意,您仍然在 job_id 欄位中看到重複項,因為 DISTINCT
運算子使用 job_id
和 salary
中的值來評估重複項,而不僅僅是 job_id
欄位中的值。
SQL DISTINCT 和 NULL
在資料庫中,NULL 表示未知或遺失的資料。
與數字、字串、日期等值不同,NULL 不等於任何東西,甚至不等於它自己。以下運算式將返回未知 (或 NULL)
NULL=NULL
Code language: PHP (php)
通常,DISTINCT
運算子會將所有 NULL 視為相同。因此,DISTINCT
運算子在結果集中僅保留一個 NULL
。
請注意,此行為在不同的資料庫產品之間可能有所不同。
例如,以下語句返回員工的相異電話號碼
SELECT DISTINCT phone_number
FROM employees
ORDER BY phone_number;
Code language: SQL (Structured Query Language) (sql)
+--------------+
| phone_number |
+--------------+
| NULL |
| 515.123.4444 |
| 515.123.4567 |
| 515.123.4568 |
| 515.123.4569 |
| 515.123.5555 |
...
Code language: plaintext (plaintext)
請注意,查詢在結果集中僅返回一個 NULL
。
摘要
- 在
SELECT
子句中使用DISTINCT
運算子,從結果集中移除重複的列。