跟随B站宋红康老师【康师傅】学习MySQL
流程控制函数可以根据不同的条件,执行不同的处理流程,可以在SQL语句中实现不同的条件选择。MySQL中的流程控制函数主要包括 IF()、IFNULL()和CASE() 函数。
函数 | 用法 |
---|---|
IF(value,value1,value2) | 如果value的值为TRUE,返回value1,否则返回value2 |
IFNULL(value1,value2) | 如果value1不为NULL,返回value1,否则返回value2 |
CASE WHEN 条件1 THEN 结果1 WHEN 条件2 THEN 结果2 …[ELSE result] END | 相当于Java中的if … else if … else … |
CASE expr WHEN 常量值1 THEN 值1 WHEN 常量值2 THEN 值2… [ELSE 值n] END | 相当于Java中的switch… case… |
示例一
SELECT IF(1 > 0,'正确','错误')
SELECT
last_name,
salary,
IF(
salary > 6000,
'低工资',
'高工资'
) AS "details"
FROM
employees ;
示例一
SELECT IFNULL(NULL,'MySQL');
SELECT
last_name,
salary * (1 + IFNULL(commission_pct, 0)) * 12 "年工资"
FROM
employees ;
示例一
SELECT
CASE
WHEN 1 > 0
THEN '1 > 0'
WHEN 2 > 0
THEN '2 > 0'
WHEN 3 > 0
THEN '3 > 0'
ELSE '(┬┬﹏┬┬)'
END "结果"
SELECT
last_name,
salary,
CASE
WHEN salary > 10000
THEN '高富帅'
WHEN salary > 80000
THEN '潜力股'
WHEN salary > 60000
THEN '小屌丝'
ELSE '小草根'
END "结果"
FROM
employees ;
示例一
SELECT
last_name,
department_id,
CASE
department_id
WHEN 10
THEN salary * 1.1
WHEN 20
THEN salary * 1.2
WHEN 30
THEN salary * 1.3
ELSE salary * 1.4
END "工资"
FROM
employees ;
SELECT
last_name,
department_id,
CASE
department_id
WHEN 10
THEN salary * 1.1
WHEN 20
THEN salary * 1.2
WHEN 30
THEN salary * 1.3
END "工资"
FROM
employees
WHERE department_id IN (10, 20, 30) ;