在数据抓取的过程中遇到了在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)