众所周知sql中条件in的值是不能超过1000个的,而mybatis可以使用动态sql拼接的方式绕开这个限制,网上看了很多例子,我感觉都不太好理解,下面介绍一个超简单的例子。
select * from user_info
where 1 = 1
<if test="userList!= null and userList.size() > 0">
and (userId in
<foreach collection="userList" open="(" close=")" separator="," item="userId" index="index">
//只需在原基础上加一个if条件,最外面加上一对括号就可以了
<if test="index != 0 and index % 999 == 0">
#{userId}) or userId in (
</if>
#{userId}
</foreach>
)
</if>
- 原来没加if条件的情况,in超过1000行:
and (userId in (1,2,3,4,5...998,999,1000,1001...))
- 加上if条件后,每隔999个位置插入一个#{userId}) or userId in (分割成两个in:
and (userId in (1,2,3,4,5...998,999) or userId in (999,1000,1001...))
虽然in太多的值会导致sql性能堪忧,但有时候身不由己,没有别的办法的时候也只能这么干了。