• sql中的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

    举例:

    1case sex when 1 then '男' when 2 then '女' else '其他' end 

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

    2case 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 ;

  • 相关阅读:
    samdump2获取虚拟机密码
    PHP执行cmd方法若干
    Aircrack-ng学习笔记之无AP破解WiFi密码
    Python基础:extend与append的区别
    Python基础:dictionary
    UVALive 3177 长城守卫
    UVALive 3902 网络
    UVA 11520 填充正方形
    UVALive 3635 分派
    UVALive 3971 组装电脑
  • 原文地址:https://www.cnblogs.com/jiangshengxiang/p/9263429.html
Copyright © 2020-2023  润新知