迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 数据库 > MySQL >

MySQL 中的 CASE WHEN

作者:迹忆客 最近更新:2023/03/13 浏览次数:

在本篇文章中,我们旨在了解如何在 MySQL 数据库中使用 CASE WHEN 语句。

处理大量数据的企业和组织需要根据特定条件过滤数据。而如果有多个条件,程序员就很难写出高效的查询来快速检索数据。

MySQL 借助 CASE WHEN 语句帮助我们执行此操作。

CASE WHEN 语句在所有处理 MySQL 数据过滤的工作场所都非常有用。让我们看看这个方法的实际效果。

但在我们开始之前,让我们通过创建一个包含几行的表 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,"Preet","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	      Preet	        Jos
5	      Hash	        Shah
6	      Sachin	    Parker
7	      David	        Miller

设置好表后,让我们使用 CASE WHEN 语句过滤这些数据。

MySQL 中的 CASE WHEN

如上所述,CASE WHEN 语句帮助我们获取满足其表达式中指定条件的值。

这是 CASE WHEN 语句的基本语法:

CASE
    WHEN condition_1 THEN output_1
    WHEN condition_2 THEN output_2
    ELSE output_3
END;

上述代码在满足 condition_1 时返回 output_1,在满足 condition_2 时返回 output_2,在不满足 condition_1condition_2 时返回 output_3

现在,让我们根据 stu_id 过滤 student_details 表。当 stu_id 小于或等于三时,我们希望打印 student with small id,当 stu_id 大于三时,我们打印 student with large id

我们可以使用以下代码执行此操作。

SELECT stu_id, stu_firstName,
CASE
    WHEN stu_id > 3 THEN 'student with greater id'
    ELSE 'student with smaller id'
END as case_result
FROM student_details;

上述查询的输出如下。

stu_id	stu_firstName	case_result
1		Preet			student with smaller id
2		Rich			student with smaller id
3		Veron			student with smaller id
4		Preet			student with greater id
5		Hash			student with greater id
6		Sachin			student with greater id
7		David			student with greater id

正如我们在上述代码块中看到的那样,stu_id 大于 3 的学生会得到 student with greater id 作为案例结果。否则,我们将得到 id 较小的学生作为案例结果。

因此,在 CASE WHEN 语句的帮助下,我们可以有效地遍历不同的条件并从 MySQL 中的表中找到匹配的数据。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

如何在 MySQL 中声明和使用变量

发布时间:2024/03/26 浏览次数:115 分类:MySQL

当你需要在 MySQL 中的脚本中存储单个值时,最好的方法是使用变量。变量有不同的种类,有必要知道何时以及如何使用每种类型。

在 MySQL 中实现刷新权限

发布时间:2024/03/26 浏览次数:211 分类:MySQL

本教程介绍了 MySQL 中的刷新权限命令,用于刷新授权表并影响允许的更改。

在 MySQL 中设置时区

发布时间:2024/03/26 浏览次数:93 分类:MySQL

在本教程中,我们将学习如何在 MySQL 服务器中更改时区。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便