当前位置 博文首页 > 缘来侍你的博客:MySQL IF和case的使用以及如何取两个字符串中间

    缘来侍你的博客:MySQL IF和case的使用以及如何取两个字符串中间

    作者:[db:作者] 时间:2021-09-16 13:32

    在做查询的时候,有时候希望状态能清楚的显示,而不是只显示1,2等

    问题:例如 数据库中某个字段1代表连载 2代表完结,我希望查询出的结果是连载或完结,而不是1或2

    解决方案:用IF语句

    if(条件,满足条件时,不满足条件)

    相当于

    if(条件){

    ? ? ? ? 满足条件时

    }else{

    ? ? ? ? 不满足条件

    }

    ?示例:

    if(over_type=1,'连载','完结') as '状态'

    问题:如果状态值很多,例如:1代表学生 2代表老师 3代表家长,空就显示空的

    这种情况用上面的IF显然不行,那么该怎么处理?

    解决方案:用case语句

    case when 条件1 then 结果1 when 条件2 then 结果2 when 条件3 then 结果3 ... else 结果4?end

    相当于

    switch (expression)
    {
    case 条件1:
      结果1;
      break;  
    case 条件2:
      结果2;
      break;
    case 条件3: 
    ??结果3;
    ? break;
    default:
      结果4
    }
    

    示例:

    case when seed=1 then '学生' when seed=2 then '教师' when seed=3 then '家长' else '' end as '角色'

    ?

    另外

    记录下MySQL如何取某个字符串中间的值

    例如:,你好,?我如何只取 你好 两个字呢?

    解决方法:

    substring_index(substring_index(字段, ',', 2) , ',', -1)

    示例:

    substring_index(substring_index(category, ',', 2) , ',', -1) as '分类'

    ?

    cs
    下一篇:没有了