How does MySQL CASE work?(MySQL CASE 是如何工作的?)
问题描述
我知道SQL的CASE
语法如下:
I know that SQL's CASE
syntax is as follows:
CASE
WHEN search_condition THEN statement_list
[WHEN search_condition THEN statement_list] ...
[ELSE statement_list]
END CASE
但是,我不明白这是如何工作的,可能是因为我将其视为一个 if
语句.
However, I don't understand how this works, possibly because I'm thinking about it as about an if
statement.
如果我在表 user_role
中有一个字段,例如,其中包含Manager"、Part Time"等名称,我如何生成字段 role_order
根据角色使用不同的数字.在本例中,如果 user_role = 'Manager' then role_order = 5".
If I have a field in table user_role
, for example, which contains names like "Manager", "Part Time" etc., how do I generate a field role_order
with a different number depending on the role. In the case of this example, "if user_role = 'Manager' then role_order = 5".
请注意,我正在寻找一个教一个人如何钓鱼的答案,而不是给一个人一条鱼的答案.
Please note I am looking for a teach a man how to fish answer rather than give a man a fish answer.
推荐答案
CASE
更像是一个 switch 语句.它有两种您可以使用的语法.第一个让你可以使用任何你想要的比较语句:
CASE
is more like a switch statement. It has two syntaxes you can use. The first lets you use any compare statements you want:
CASE
WHEN user_role = 'Manager' then 4
WHEN user_name = 'Tom' then 27
WHEN columnA <> columnB then 99
ELSE -1 --unknown
END
第二种样式适用于您只检查一个值的情况,并且更加简洁:
The second style is for when you are only examining one value, and is a little more succinct:
CASE user_role
WHEN 'Manager' then 4
WHEN 'Part Time' then 7
ELSE -1 --unknown
END
这篇关于MySQL CASE 是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:MySQL CASE 是如何工作的?


基础教程推荐
- Sql Server 字符串到日期的转换 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01