SQL SELECT DISTINCT

SQL SELECT DISTINCT 语句用来从数据表的列中选取唯一的值,而把重复的值从结果中剔除。在 MS SQL Server, Oracle, MySQL 中用法相同。

SQL SELECT DISTINCT 语法

SELECT DISTINCT 列1, 列2, ...
FROM 表

SQL SELECT DISTINCT 范例

数据表: Employees

EmployeeId FirstName LastName Department Salary
203 Mary Fox Finance 78000
204 Joe Lanyon Finance 45800
205 Sally Daff Finance 57000
206 Grace Salter Finance 62000
302 James Fox Development 75000
303 Dona Lanyon Development 55000
304 Tony Oakes Development 49000

选择所有唯一的LastName:

SELECT DISTINCT LastName
FROM Employees

上述语句的执行结果会是:

LastName
Fox
Lanyon
Daff
Salter
Oakes

DISTINCT 子句可以用于超过一个列:

SELECT DISTINCT FirstName, LastName
FROM Employees

上面的语句将会返回 FirstName 和 LastName 组合的唯一值。结果会类似于:

FirstName LastName
Mary Fox
Joe Lanyon
Sally Daff
Grace Salter
James Fox
Dona Lanyon
Tony Oakes