浅析如何在select中使用条件判断语句实现根据不同类型取不同表中的字段的值赋值给同一个字段:SQL之case when then用法

一、项目实例

  我们有个订单,有不同的产品类型,比如课程、云市场类,那么订单实体类的 imageUrl 就得取自不同的表了。比如 type = 课程时,imageUrl 数据得从课程表里取;type = 云市场时,imageUrl 数据得从云市场表里取。

  那么如何写 sql 呢?利用 case when then 语句。

select
......
co.payment_status paymentStatus,
(case when co.type = 6 then cms.image_url else cc.image_url end) imageUrl,
......
from cs_or co
left join cs_cou cc on co.p_id = cc.p_id and co.type = 2
left join cs_mar_pur cm on co.o_id = cm.o_id and co.type = 6
left join cs_mar_ser cms on cm.mar_ser_id = cms.id and co.type = 6
......

  重点就是这一句了:(case when co.type = 6 then cms.image_url else cc.image_url end) imageUrl

  最开始我写的是:(case when co.type = 6 then cm.image_url else cc.image_url end) imageUrl,然后一直报一个错:

Caused by: org.postgresql.util.PSQLException: ERROR: column cm.image_url does not exist
建议:Perhaps you meant to reference the column "cc.image_url".

  报错说的是:ERROR: column cm.image_url does not exist,cm 表的 image_url 不存在,而我一直以为 cm 表就有,还挺纳闷的还以为不支持 then 字段 的写法,后来发现原来 cm 表是购买信息表,并不是商品信息表 cms,image_url 是存在商品信息表 cms 里的,所以加上 cms 表之后就正常了。

  踩坑也不错,以后再碰到这种报错就知道原因了,其实事后一看,报错信息挺明显的,就是说的字段 image_url 不存在。

二、SQL之 case when then 用法

1、case具有两种格式。简单case函数和case搜索函数。

-- 简单case函数
case sex
    when '1' then ''
    when '2' then '女’
    else '其他' end

-- case搜索函数
case when sex = '1' then ''
    when sex = '2' then ''
    else '其他' end  

  这两种方式,可以实现相同的功能。简单case函数的写法相对比较简洁,但是和case搜索函数相比,功能方面会有些限制,比如写判定式。

  还有一个需要注意的问题,case函数只返回第一个符合条件的值,剩下的case部分将会被自动忽略。

--比如说,下面这段sql,你永远无法得到“第二类”这个结果
case when col_1 in ('a','b') then '第一类'
    when col_1 in ('a') then '第二类'
    else '其他' end  

 2、then 后面是可以跟字段的

select age_level,
(case when age_level = 1 then Chile_num when age_level=2 then adult_num when age_level=3 then older_num end) as num,
(case when age_level = 1 then Chile_pay when age_level=2 then adult_pay when age_level=3 then older_pay end) as pay,
(case when age_level = 1 then Chile_time when age_level=2 then adult_time when age_level=3 then older_time end) as time
from table

  这个示例就跟我的项目示例遇到的很像了。

posted @ 2021-08-26 22:33  古兰精  阅读(1560)  评论(0编辑  收藏  举报