IF()函数的使用
IF(expr1,expr2,expr3),如果expr1的值为true,则返回expr2的值,如果expr1的值为false,则返回expr3的值。
SELECT IF(TRUE,'A','B'); -- 输出结果:A
SELECT IF(FALSE,'A','B'); -- 输出结果:B
IFNULL()函数的使用
IFNULL(expr1,expr2),如果expr1的值为null,则返回expr2的值,如果expr1的值不为null,则返回expr1的值。
SELECT IFNULL(NULL,'B'); -- 输出结果:B
SELECT IFNULL('HELLO','B'); -- 输出结果:HELLO
NULLIF()函数的使用
NULLIF(expr1,expr2),如果expr1=expr2成立,那么返回值为null,否则返回值为expr1的值。
SELECT NULLIF('A','A'); -- 输出结果:null
SELECT NULLIF('A','B'); -- 输出结果:A
使用case简单函数
case `gender`
when 1 then '男'
when 2 then '女'
else '未知'
endcase
when gender = 1 then '男'
when gender = 2 then '女'
else '未知'
endselect `id`, `name`, `gender`,
(case `gender`
when 1 then '男'
when 2 then '女'
else '未知'
end) as '性别',
`country_code`
from test_user;SELECTNAME '英雄',CASE NAMEWHEN '德莱文' THEN'斧子'WHEN '德玛西亚-盖伦' THEN'大宝剑'WHEN '暗夜猎手-VN' THEN'弩'ELSE'无'END '装备'
FROMuser_info;# when 表达式中可以使用 and 连接条件
SELECTNAME '英雄',age '年龄',CASEWHEN age < 18 THEN'少年'WHEN age < 30 THEN'青年'WHEN age >= 30AND age < 50 THEN'中年'ELSE'老年'END '状态'
FROMuser_info;select case a.positionwhen '0' then '未知' when '1' then '首屏' when '3' then '首屏以下'when '4' then '页面顶部' when '5' then '页面底部' when '6' then '侧边栏'when '7' then '全屏' when '8' then '二屏' when '9' then '三屏'when '10' then '四屏' when '11' then '五屏' when '12' then '五屏以下'end as pp,case a.typewhen '0' then 'Banner'when '1' then 'Video'end as tt,case a.DeviceTypewhen '0' then 'phone' when '1' then 'tablet' when '2' then 'pc' when '3' then 'TV'end as tttfrom publisher p,adplacement awhere a.PublisherId = p.idinto outfile '/tmp/ad.csv' fields terminated by ',' optionally enclosed by '"' escaped by '"' lines terminated by '\r\n';