MySQL CASE 是如何工作的?

How does MySQL CASE work?(MySQL CASE 是如何工作的?)
本文介绍了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 是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)