1. 程式人生 > >關於sql中or與and的執行順序

關於sql中or與and的執行順序

  <select id="countAssetTab"  resultType="Integer" parameterType="HashMap">
    	SELECT COUNT(1) FROM TTRD_ASSET_MANAGE_PLAN_EXTEND 
          <where>
	      	<if test="i_code != null and i_code !=''">
	      		AND (I_CODE = #{i_code}
	      		OR I_CODE = CONCAT(#{i_code},'(temp)'))
	      	</if>
	      	<if test="a_type != null and a_type !=''">
	      		AND A_TYPE = #{a_type}
	      	</if>
	      	 AND ZMZC_FLAG = 1
	     </where>  
    </select>
    如上,是我在公司專案中寫的程式碼,我遇到的問題是,在
            AND (I_CODE = #{i_code}
	    OR I_CODE = CONCAT(#{i_code},'(temp)')) 
程式碼部分我第一次沒有應用括號的情況下,查找出來的資料是不正確的,因為在sql語句中的執行順序是not>and>or的,
因此在or的部分沒有使用括號的情況下,將當前的語句變成了
            AND (I_CODE = #{i_code})
	    OR (I_CODE = CONCAT(#{i_code},'(temp)')
            AND A_TYPE = #{a_type}
            AND ZMZC_FLAG = 1)
導致一直查詢到的資料不正確。