在MyBatis中进行多条件查询可以使用动态SQL来构建查询语句。
以下是在MyBatis中几种常见的多条件查询语句:
1、使用if
<select id="findByConditions" parameterType="map" resultType="YourResultType">
SELECT * FROM your_table
WHERE 1=1
<if test="condition1 != null">
AND condition1 = #{condition1}
</if>
<if test="condition2 != null">
AND condition2 = #{condition2}
</if>
...
</select>
2、使用where改进1
<select id="findByConditions" parameterType="map" resultType="YourResultType">
SELECT * FROM your_table
<where>
<if test="condition1 != null">
AND condition1 = #{condition1}
</if>
<if test="condition2 != null">
AND condition2 = #{condition2}
</if>
...
</where>
</select>
使用where可以省略掉无条件的and
3、使用choose、when和otherwise
<select id="findByConditions" parameterType="map" resultType="YourResultType">
SELECT * FROM your_table
<where>
<choose>
<when test="condition1 != null">
AND condition1 = #{condition1}
</when>
<when test="condition2 != null">
AND condition2 = #{condition2}
</when>
<otherwise>
AND defaultCondition = #{defaultCondition}
</otherwise>
</choose>
</where>
</select>