在使用mybatis動態sql時,遇到如下問題:
select * from table a where a.project_id=#{projectid} and a.id != #{id} and a.status=3 and a.id_card = #{code} or a.unit_code = #{code}
想要將其優化為:
select * from table a where a.project_id=#{projectid} and a.id != #{id} and a.status=3 and <if test="type == 'idcard'">a.id_card = #{code}</if> <if test="type == 'unitcode'">a.unit_code = #{code}</if>
但優化后運行會報錯(3種寫法都會報badsql)。
解決方法
正確的寫法如下:
select * from table a <where> a.project_id=#{projectId} and a.id != #{id} and a.status=3 <choose> <when test="type == idCard"> and a.id_card = #{code} </when> <when test="type == unitCode">and a.unit_code = #{code}</when> <otherwise> </otherwise> </choose> </where>
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END