淺析如何在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

  這個示例就跟我的項目示例遇到的很像了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM