MySQL中根據if標籤實現多條件模糊查詢(動態SQL語句)
阿新 • • 發佈:2019-01-28
if標籤
if標籤可用在許多型別的sql語句中,我們以查詢為例。首先看一個很普通的查詢:
Xml程式碼- <!-- 查詢學生list,like姓名 -->
- <select id="getStudentListLikeName" parameterType="StudentEntity" resultMap="studentResultMap">
- SELECT * from STUDENT_TBL ST
-
WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')
- </select>
但是此時如果studentName或studentSex為null,此語句很可能報錯或查詢結果為空。此時我們使用if動態sql語句先進行判斷,如果值為null或等於空字串,我們就不進行此條件的判斷,增加靈活性。
引數為實體類StudentEntity。將實體類中所有的屬性均進行判斷,如果不為空則執行判斷條件。
Xml程式碼- <!-- 2 if(判斷引數) - 將實體類不為空的屬性作為where條件 -->
-
<select id="getStudentList_if" resultMap="resultMap_studentEntity"
- SELECT ST.STUDENT_ID,
- ST.STUDENT_NAME,
- ST.STUDENT_SEX,
- ST.STUDENT_BIRTHDAY,
- ST.STUDENT_PHOTO,
- ST.CLASS_ID,
- ST.PLACE_ID
-
FROM STUDENT_TBL ST
- WHERE
- <if test="studentName !=null ">
- ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')
- </if>
- <if test="studentSex != null and studentSex != '' ">
- AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}
- </if>
- <if test="studentBirthday != null ">
- AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}
- </if>
- <if test="classId != null and classId!= '' ">
- AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR}
- </if>
- <if test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' ">
- AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR}
- </if>
- <if test="placeId != null and placeId != '' ">
- AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}
- </if>
- <if test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' ">
- AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}
- </if>
- <if test="studentId != null and studentId != '' ">
- AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}
- </if>
- </select>