SQL中的if()和ifnull() 的用法和区别

if()&ifnull()

if()把salary表中的女改成男,男改成女:

update salary set sex = if( sex = ‘男’,‘女’,‘男’);

if(true,a,b), if(false,a,b) 这个就是第一个如果是true,就等于a,false就等于b,有点像三元表达式

ifnull(null, a),ifnull(a,b), ifnull里有两个数,如果第一个不是null,是a非null,就都等于a, 如果a=Null,就都为a。

eg:

SELECT IFNULL(NULL,“11”); -> 11

SELECT IFNULL(“00”,“11”); -> 00

与if()和ifnull()作用相同的,还有一个,就是case when then else end

举例:

  1. case sex when 1 then ‘男’ when 2 then ‘女’ else ‘其他’ end

    这个就是把表中的sex字段1,换成男,2换成女,都不是换成其他,也可以写作:

  2. case when sex = 1 then ‘男’ when sex = 2 then ‘女’ else ‘其他’ end

1叫做简单case函数 2叫做case搜索函数,功能相同,但是case搜索函可以写条件判定,比如不等于,而简单case函数只能是=

还有一点要注意的是:case函数如果满足第一个条件,就会忽略第二个条件

case when id in (1,2) then ‘第一类’ when id in (1) then ‘第二类’ esle ‘其他’ end

你永远不会得到第二类这个结果

select name,id ,sex,(case sex when 1 then ‘男’ when 2 then ‘女’ esle ‘其他’ end ) 性别 from users

重点: case和sum结合还可以实现分段统计

select sum(case sex when 1 then 1 else 0 end) 男性,sum(case sex when 2 then 1 else 0 end) 女性,sum(case when sex <> 1 and sex <> 2 then 1 else 0 end)其他 from users

文章开头的那题:

select (case sex when ‘男’ then ‘女’ when ‘女’ then ‘男’ end ) from salary;

update salary set sex = case sex when ‘f’ then ‘m’ else ‘f’ end ;
转载地址:
http://www.cnblogs.com/jiangshengxiang/p/9263429.html

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值