MySQL 中的 CASE WHEN
在本教程中,我们旨在了解如何在 MySQL 数据库中使用 CASE WHEN
语句。
处理大量数据的企业和组织需要根据特定条件过滤数据。而如果有多个条件,程序员就很难写出高效的查询来快速检索数据。
MySQL 借助 CASE WHEN
语句帮助我们执行此操作。
CASE WHEN
语句在所有处理 MySQL 数据过滤的工作场所都非常有用。让我们看看这个方法的实际效果。
但在我们开始之前,让我们通过创建一个包含几行的表 student_details
来创建一个虚拟数据集。
-- create the table student_details
CREATETABLEstudent_details(stu_idint,stu_firstNamevarchar(255)DEFAULTNULL,stu_lastNamevarchar(255)DEFAULTNULL,primarykey(stu_id));-- insert rows to the table student_details
INSERTINTOstudent_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");
上面的查询创建了一个表,其中包含学生的名字和姓氏。要查看数据中的条目,我们使用以下代码:
SELECT*FROMstudent_details;
上面的代码将给出以下输出:
stu_id stu_firstName stu_lastName
1 Preet Sanghavi
2 Rich John
3 Veron Brow
4 Preet Jos
5 Hash Shah
6 Sachin Parker
7 David Miller
设置好表后,让我们使用 CASE WHEN
语句过滤这些数据。
MySQL 中的 CASE WHEN
如上所述,CASE WHEN
语句帮助我们获取满足其表达式中指定条件的值。
这是 CASE WHEN
语句的基本语法:
CASEWHENcondition_1THENoutput_1WHENcondition_2THENoutput_2ELSEoutput_3END;
上述代码在满足 condition_1
时返回 output_1
,在满足 condition_2
时返回 output_2
,在不满足 condition_1
和 condition_2
时返回 output_3
。
现在,让我们根据 stu_id
过滤 student_details
表。当 stu_id
小于或等于三时,我们希望打印 student with small id
,当 stu_id
大于三时,我们打印 student with large id
。
我们可以使用以下代码执行此操作。
SELECTstu_id,stu_firstName,CASEWHENstu_id>3THEN'student with greater id'ELSE'student with smaller id'ENDascase_resultFROMstudent_details;
上述查询的输出如下。
stu_idstu_firstNamecase_result1Preetstudentwithsmallerid2Richstudentwithsmallerid3Veronstudentwithsmallerid4Preetstudentwithgreaterid5Hashstudentwithgreaterid6Sachinstudentwithgreaterid7Davidstudentwithgreaterid
正如我们在上述代码块中看到的那样,stu_id
大于 3 的学生会得到 student with greater id
作为案例结果。否则,我们将得到 id 较小的学生
作为案例结果。
case_result
以获得更好的可读性,并在 MySQL 中使用 as AS
关键字。因此,在 CASE WHEN
语句的帮助下,我们可以有效地遍历不同的条件并从 MySQL 中的表中找到匹配的数据。