在資料抓取的過程中遇到了在sql語句中實現選擇判斷的需求,參考原來的指令碼發現其中有一個DECODE(value, if1, then1, if2,then2,
if3,then3, . . . else )函數可以實現這種需求,拿過來用上後報錯,一查發現這個函數在oracle資料裡可以使用,mySql資料庫就不能使用了,那麼mysql該如何?呢,網上的資料很多,只要找出問題,解決的辦法網上一般都會找到,下面就介紹我用的辦法。
舉例:oracle中(decode):
SELECT sum(sti.find_questions) as findtotal, sum(sti.update_questions) as updatetotal, round(100 * ((decode(sum(sti.update_questions), null, 0, sum(sti.update_questions))) / ((decode(sum(sti.update_questions), null, 0, sum(sti.update_questions)))) as zgl_0 FROM yujing.special_task_inspect sti where task_id = ? and sti.inspect_time >= ? and sti.inspect_time <= ?
對應mysql中(select case when *** then *** else *** end):
SELECT sum(sti.find_questions) as findtotal, sum(sti.update_questions) as updatetotal, round(100 * ((select case when sum(sti.update_questions) = null then 0 else sum(sti.update_questions) end) / (select case when sum(sti.find_questions) = null then 0 else sum(sti.find_questions) end))) as zgl_0 FROM yujing.special_task_inspect sti where task_id = ? and sti.inspect_time >= ? and sti.inspect_time <= ?
總結:只要找到了問題的關鍵點,解決問題就會變的很容易。
此外,還可以在Order by中使用Decode。
例如:表table_subject,有subject_name列。要求按照:語、數、外的順序進行排序。這時,就可以非常輕鬆的使用Decode完成要求了。
select * from table_subject order bydecode(subject_name, '語文', 1, '數學', 2, '外語',3)