1. 程式人生 > >MySQL中根據if標籤實現多條件模糊查詢(動態SQL語句)

MySQL中根據if標籤實現多條件模糊查詢(動態SQL語句)

 if標籤

 if標籤可用在許多型別的sql語句中,我們以查詢為例。首先看一個很普通的查詢:

Xml程式碼  收藏程式碼
  1. <!-- 查詢學生list,like姓名 -->  
  2. <select id="getStudentListLikeName" parameterType="StudentEntity" resultMap="studentResultMap">  
  3.     SELECT * from STUDENT_TBL ST   
  4. WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')  
  5. </select>  

但是此時如果studentName或studentSex為null,此語句很可能報錯或查詢結果為空。此時我們使用if動態sql語句先進行判斷,如果值為null或等於空字串,我們就不進行此條件的判斷,增加靈活性。

引數為實體類StudentEntity。將實體類中所有的屬性均進行判斷,如果不為空則執行判斷條件。

Xml程式碼  收藏程式碼
  1. <!-- 2 if(判斷引數) - 將實體類不為空的屬性作為where條件 -->  
  2. <select id="getStudentList_if" resultMap="resultMap_studentEntity"
     parameterType="liming.student.manager.data.model.StudentEntity">  
  3.     SELECT ST.STUDENT_ID,  
  4.            ST.STUDENT_NAME,  
  5.            ST.STUDENT_SEX,  
  6.            ST.STUDENT_BIRTHDAY,  
  7.            ST.STUDENT_PHOTO,  
  8.            ST.CLASS_ID,  
  9.            ST.PLACE_ID  
  10.       FROM STUDENT_TBL ST   
  11.      WHERE  
  12.     <if test="studentName !=null ">  
  13.         ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')  
  14.     </if>  
  15.     <if test="studentSex != null and studentSex != '' ">  
  16.         AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}  
  17.     </if>  
  18.     <if test="studentBirthday != null ">  
  19.         AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}  
  20.     </if>  
  21.     <if test="classId != null and classId!= '' ">  
  22.         AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR}  
  23.     </if>  
  24.     <if test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' ">  
  25.         AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR}  
  26.     </if>  
  27.     <if test="placeId != null and placeId != '' ">  
  28.         AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}  
  29.     </if>  
  30.     <if test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' ">  
  31.         AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}  
  32.     </if>  
  33.     <if test="studentId != null and studentId != '' ">  
  34.         AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}  
  35.     </if>   
  36. </select>