Skip to content

choose

<choose> 是 MyBatis 动态 SQL 里用来实现**“多选一”逻辑**的标签,类似 Java 里的:

java
if (...) {
} else if (...) {
} else {
}
xml
<choose>
    <when test="条件1">
        SQL1
    </when>

    <when test="条件2">
        SQL2
    </when>

    <otherwise>
        SQL默认
    </otherwise>
</choose>
xml
<select id="queryUser" resultType="User">
    SELECT * FROM user
    <where>
        <choose>
            <when test="name != null and name != ''">
                name = #{name}
            </when>

            <when test="phone != null and phone != ''">
                phone = #{phone}
            </when>

            <otherwise>
                status = 1
            </otherwise>
        </choose>
    </where>
</select>