SELECT DISTINCT
语句从数据库表中检索唯一值。
示例
-- select the unique ages from the Customers table
SELECT DISTINCT age
FROM Customers;
在这里,SQL 命令从 Customers 表中选择年龄的唯一值。
SQL SELECT DISTINCT 语法
SELECT DISTINCT column1, column2 ...
FROM table;
这里,
- `column1, column2, ...` 是表中的列
table
是我们从中检索唯一列的表名。
示例:SQL SELECT DISTINCT
-- select the unique countries from the customers table
SELECT DISTINCT country
FROM Customers;
在这里,SQL 命令从 Customers 表中选择唯一的国家/地区。

多列上的 SQL DISTINCT
我们也可以将 SELECT DISTINCT
与多列一起使用。例如:
-- select rows if the first name and country of a customer is unique
SELECT DISTINCT country, first_name
FROM Customers;
在这里,如果 country 和 first_name 的组合是唯一的,则该命令会选择行。这意味着结果中每个 country 和 first_name 的对只会出现一次。

DISTINCT 与 COUNT
我们可以将 SQL DISTINCT
与 COUNT() 函数一起使用来计算唯一行的数量。
让我们看一个例子。
-- count the unique countries where customers are from
SELECT COUNT(DISTINCT country)
FROM Customers;
在这里,SQL 命令返回唯一国家/地区的计数。

更多 SQL DISTINCT
让我们看一个例子:
-- with distinct
SELECT DISTINCT country
FROM Customers;
-- with group by
SELECT country
FROM Customers
GROUP BY country;
在这里,这两个 SQL 命令相似,都从 Customers 表中返回唯一的国家/地区。
DISTINCT
- 从 Customers 表中选择唯一的国家/地区名称,确保每个国家/地区只列出一次。GROUP BY
- 也从 Customers 中选择唯一的国家/地区名称,通过分组实现与DISTINCT
相同的结果。
要了解更多信息,请访问 SQL GROUP BY。
让我们看一个例子:
-- with order by
SELECT DISTINCT age
FROM Customers
ORDER BY age DESC;
在这里,SQL 命令从 Customers 表中选择唯一的年龄并按降序排列。
要了解更多信息,请访问 SQL ORDER BY。
当您只想在结果集中返回唯一(distinct)值时,使用 SELECT DISTINCT
语句。
而没有 DISTINCT
关键字的常规 SELECT
语句会检索指定列中的所有行,包括重复值。
让我们看一个例子。
示例:SELECT DISTINCT
-- select distinct countries from the Customers table
SELECT DISTINCT country
FROM Customers;
此命令将每个国家/地区仅返回一次,无论它在 Customers 表中出现多少次。
示例:SELECT
-- select all countries from the Customers table
SELECT country
FROM Customers;
此 SQL 命令将从 Customers 表中返回所有国家/地区条目,包括重复项。
要了解更多信息,请访问 SQL SELECT。