leetcode 1873,查询语句中存在判断赋值的字段,第一个进入脑海的方案就是case when,解题后发现mysql的if也是很好
力扣 1873
题解
select employee_id,
case when mod(employee_id, 2)>0 and LEFT(name, 1) <> 'M' then salary else 0 end bonus
from Employees order by employee_id asc;
select employee_id, if(employee_id % 2 != 0 and left(name, 1) != 'M', salary, 0) as bonus
from Employees
order by employee_id;
case when解释
(1)
CASE input_expression
WHEN when_expression THEN
result_expression [...n ] [
ELSE
else_result_expression
END
(2)
CASE
WHEN Boolean_expression THEN
result_expression [...n ] [
ELSE
else_result_expression
END
if解释
IF(expr1,expr2,expr3)
如果 expr1 是TRUE ,则 IF()的返回值为expr2; 否则返回值则为 expr3。
网友评论