mybatis动态SQL 使用foreach函数 怎么解决第一个拼接语句多一个运算符
如果使用
- 使用
函数判断是否为第一个元素,如果是则不拼接运算符
例如:
<select id="selectByIds" parameterType="list" resultType="User">
SELECT * FROM user WHERE id IN
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
<if test="index > 0">AND</if>
#{item}
</foreach>
</select>
- 将第一个元素作为一个特殊情况处理,先将其拼接到SQL语句中,然后在
函数中使用separator属性指定分隔符,这样就可以避免第一个元素多拼接一个运算符。
例如:
<select id="selectByIds" parameterType="list" resultType="User">
SELECT * FROM user WHERE id = #{list[0]}
<foreach item="item" index="index" collection="list" open=" AND id IN (" separator="," close=")">
#{item}
</foreach>
</select>
``
原文地址: https://www.cveoy.top/t/topic/fpLf 著作权归作者所有。请勿转载和采集!