在我們開發中,有時要對數據庫中的數據按照條件進行查詢,用到if else類似的語句進行判斷,那么if else語句只有在存儲過程,觸發器之類的才有,但是要在sql上當滿足某種條件上要取不同的字段值,剛開始我還不會,最后查了資料,發現使用case when語句就可以解決,而且各種數據庫都支持。
語法:
case when 條件1 then 結果1 when 條件2 then 結果2 else 結果N end
可以有任意多個條件,如果沒有默認的結果,最后的else也可以不寫,
select case when col1 > 1 then col2 else col3 end from XXXtable
一、[基本查詢語句展示優化]
Sql代碼
#根據type查詢 SELECT id,title,type FROM table WHERE type=1; SELECT id,title,type FROM table WHERE type=2;
用if優化Sql代碼
#if(expr,true,false) SELECT id,title,type,if(type=1,1,0) as type1,if(type=2,1,0) as type2 FROM table; SELECT id,title,type,if(type=1,1,0) as type1,if(type=2,1,0) as type2 FROM table;
用case when優化Sql代碼
#case...when...then...when...then...else...end SELECT id,title,type,case type WHEN 1 THEN 'type1' WHEN 2 THEN 'type2' ELSE 'type error' END as newType FROM table;
二、[統計數據性能優化]
Sql代碼
#兩次查詢不同條件下的數量 SELECT count(id) AS size FROM table WHERE type=1 SELECT count(id) AS size FROM table WHERE type=2
用if優化Sql代碼
#sum方法 SELECT sum(if(type=1, 1, 0)) as type1, sum(if(type=2, 1, 0)) as type2 FROM table #count方法 SELECT count(if(type=1, 1, NULL)) as type1, count(if(type=2, 1, NULL)) as type2 FROM table #親測二者的時間差不多 #建議用sum,因為一不注意,count就會統計了if的false中的0
用case when優化Sql代碼
#sum SELECT sum(case type WHEN 1 THEN 1 ELSE 0 END) as type1, sum(case type WHEN 2 THEN 1 ELSE 0 END) as type2 FROM table #count SELECT count(case type WHEN 1 THEN 1 ELSE NULL END) as type1, count(case type WHEN 2 THEN 1 ELSE NULL END) as type2 FROM table
獲取更多精彩內容,學習資料,視頻等,請關注微信公眾號【程序員Style】,回復關鍵字即可。
