在使用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 <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>
原因:
原查詢語句中使用 or 條件連接兩個 if 條件,會導致拼接到 sql 時的語法錯誤。優化后的查詢語句使用 choose when otherwise 語法結構,可以根據不同的測試條件動態選擇拼接的 sql 片段,避免了語法錯誤。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END