zoukankan      html  css  js  c++  java
  • 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 ;

  • 相关阅读:
    2019 年值得关注的 23 个开发者博客
    牛津词典 2018 年度词汇 ——「有毒」!
    17 个关于雪花的有趣事实🌨❄️❄️❄️
    Google 里的软件工程学
    作为软件工程师,如何进行知识管理
    x == (x = y) 不等于 (x = y) == x ?
    Docker-compose编排微服务顺序启动
    Ubuntu 20.04 修改字体、调整缩放
    How To Upgrade Ubuntu To 20.10
    写给工程师的 Ubuntu 20.04 最佳配置指南
  • 原文地址:https://www.cnblogs.com/jiangshengxiang/p/9263429.html
Copyright © 2011-2022 走看看