MySQL 中的 CASE 语句
Preet Sanghavi
2022年5月14日
MySQL
MySQL Statement

在本教程中,我们旨在学习如何在 MySQL 中使用 CASE
语句。
当满足第一个条件时,CASE
语句继续执行条件并返回一个值(类似于 IF-THEN-ELSE
语句)。当条件为真时,程序将停止读取并返回结果。
如果没有一个条件为真,它将返回 ELSE
子句中的值。如果代码中没有 ELSE
部分,程序将返回 NULL
。
case 语句的语法可以表示为:
case when condition then result_1 else result_2 end;
让我们试着通过一个例子来了解更多关于这个语句的信息。
然而,在我们开始之前,我们创建了一个虚拟数据集来使用。在这里,我们创建了一个表,student_details
,以及其中的几行。
-- 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,"Geo","Jos"),
(5,"Hash","Shah"),
(6,"Sachin","Parker"),
(7,"David","Miller");
上面的查询创建了一个表以及其中包含学生名字和姓氏的行。要查看数据中的条目,我们使用以下代码:
SELECT * FROM student_details;
上述代码将给出以下输出:
stu_id stu_firstName stu_lastName
1 Preet Sanghavi
2 Rich John
3 Veron Brow
4 Geo Jos
5 Hash Shah
6 Sachin Parker
7 David Miller
现在,当学生的名字是 Preet
时,让我们的目标是打印 Yes
和学生的姓氏;否则,我们打印 No
。
MySQL 中的 CASE
语句
正如前面的语法所见,MySQL 中的 CASE
语句需要一个条件。这类似于 IF..ELSE..
语句。
我们可以使用以下代码示例在 MySQL 中获得所需的结果:
SELECT stu_lastName,
CASE stu_firstName
WHEN 'Preet' THEN 'Yes'
ELSE 'No'
END
AS RESULT
FROM student_details;
上述代码获取每个学生的姓氏以及名为 result
的新列。如果学生的名字是 Preet
,则此结果列具有 Yes
。
上面代码的输出可以可视化如下。
stu_lastName RESULT
Sanghavi Yes
John No
Brow No
Jos No
Shah No
Parker No
Miller No
同样,我们可以使用 CASE
语句来利用数据并满足我们的要求。CASE
语句的替代方案是 MySQL 中的 IF
语句。
因此,在本教程的帮助下,我们现在可以在 MySQL 中成功实现 CASE
语句。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Preet Sanghavi