今天在寫業務的時候,碰到一個SQL提速的問題,剛開始的時候一條條的update,那個速度慢到我吐血,上批量。
但是在批量的時候不是簡單無腦根據一個條件去update全部(那這樣的話,慢個屁啊)。每次update都要判斷條件,例如簡單的都是對應每個ID。可能我太菜了,竟然一時之間不知道怎么寫了。再次留下了沒有技術的淚水。不怕,我是有度娘和Google的孩子。然后找到了方法記錄一下。
解決辦法就是說使用case when。
語法就是:
update table set field=
case field1
when a then b
when c then d
end,
field2 =
case field1
when a then e
when c then f
where field1 in (a,c);
這樣就可以根據條件去update了
當然啦,mybatis怎么寫呢,我習慣用注解,簡單,直接。所以也貼一下mybatis注解的寫法吧,這里用到了script 里面的for循環,不會的可以自己學習一下哦,不過我覺得這個一眼就會啦
@Update({"<script>",
"update <table> set <field> = CASE <field1> ",
"<foreach collection='lst' item='task' index='index' separator=''>",
"WHEN #{task.<field1>} THEN #{task.<field>}",
"</foreach>",
"END, ",
"<field2> = CASE <field1> ",
"<foreach collection='lst' item='task' index='index' separator=''>",
"WHEN #{task.<field1>} THEN #{task.<field2>}",
"</foreach>",
"END where <field1> in (${ids});",
"</script>"
})
void updateCrmBatch(@Param("lst") List<Object> lst,@Param("ids") String ids);
ok,打完收工,我波哥說我懶惰了,看起我要勤奮才行啊~加油~~~~