在 MySQL 中选择唯一值

Preet Sanghavi 2022年5月13日
在 MySQL 中选择唯一值

在本教程中,我们旨在了解如何在 MySQL 数据库中查找唯一值。

MySQL 为我们提供了一个有用的语句来从指定表的特定列中查找不同或不同值的总数。该语句是 SELECT DISTINCT

这通常被企业和企业用来在其数据库中查找不同用户或客户的列表或计数。让我们看看这个方法的实际效果。

但是,首先,让我们创建一个虚拟数据集。

-- create the table student_details
CREATE TABLE student_details(
	stu_id int,
	stu_firstName varchar(255) DEFAULT NULL,
	stu_lastName varchar(255) DEFAULT NULL,
	primary key(stu_id)
);
-- insert rows to the table student_details
INSERT INTO student_details(stu_id,stu_firstName,stu_lastName) 
 VALUES(1,"Preet","Sanghavi"),
 (2,"Rich","John"),
 (3,"Veron","Brow"),
 (4,"Preet","Jos"),
 (5,"Hash","Shah"),
 (6,"Sachin","Parker"),
 (7,"David","Miller");

在 MySQL 中使用 SELECT DISTINCT 选择唯一值

MySQL 中的 SELECT DISTINCT 语句帮助我们获取特定表中的唯一值。SELECT DISTINCT 语句的基本语法如下。

SELECT DISTINCT column_name
FROM name_of_the_table;

上述代码返回来自列 column_name 的不同条目,这些条目可能有也可能没有重复条目。

让我们从 student_details 表中获取具有不同名字的所有学生。与学生的名字值关联的列是 stu_firstName

让我们使用 SELECT DISTINCT 来完成这项任务。我们可以利用以下查询从 student_details 表中获取不同或唯一的名字值。

SELECT DISTINCT stu_firstName
FROM student_details;

上述查询的输出如下。

stu_firstName
Preet
Rich
Veron
Hash
Sachin
David

如上面的代码块所示,在我们的 student_details 表中添加的七行中,我们只有六个唯一的名字。因此,输出只有六个名称,因为 Preet 在我们的列 stu_firstName 中重复了两次。

如果我们只想找到唯一值的总数,我们可以使用以下语法。

SELECT COUNT(DISTINCT(column_name))
from name_of_the_table

在我们的例子中,我们可以使用以下查询从 stu_firstName 列中查找学生的唯一名字的数量。

SELECT COUNT(DISTINCT(stu_firstName)) as total_unique_first_names
from student_details

上述代码块的输出如下。

total_unique_first_names
6

因此,在 SELECT DISTINCT 语句的帮助下,我们可以有效地找到不同条目的总数或从 MySQL 中的表中获取特定列的所有唯一值。

作者: Preet Sanghavi
Preet Sanghavi avatar Preet Sanghavi avatar

Preet writes his thoughts about programming in a simplified manner to help others learn better. With thorough research, his articles offer descriptive and easy to understand solutions.

LinkedIn GitHub

相关文章 - MySQL Select