Mybatis 动态 SQL 查询中,如何优化包含多个条件且使用 or 连接的查询语句?

Mybatis 动态 SQL 查询中,如何优化包含多个条件且使用 or 连接的查询语句?

mybatis动态sql查询优化

在使用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
喜欢就支持一下吧
点赞15 分享