今天排查一個mybatis查詢的問題,用的動態sql語句結果發現個問題。在mybatis中 or 的位置不同也會影響查詢結果。上代碼:
這是有問題的代碼
<select id="queryComissionRecord" resultType="ComissionRecordResult"> select sum(t.amount) as transferAmount, t.agentName as agentName, t.tillNumber as tillNumber, t.agentRealName as realName, count(*) as transactionNumber, sum(t.comission) as agentComissionAmount, sum(t.parentComission) as superAgentComissionAmount from comission_record t where 1=1 <if test="name != null and name != ''"> and t.agentName=#{name} or t.agentRealName=#{name} </if> <if test="tillNumber != null and tillNumber != ''"> and t.tillNumber=#{tillNumber} </if> and t.parentTillNumber=#{supAgentTillNumber} and DATE_FORMAT( startTime, '%Y%m' ) = DATE_FORMAT(#{month} , '%Y%m' ) and t.status in (0) group by agentName order by tillNumber desc </select>
這是沒問題的代碼1
<select id="queryComissionRecord" resultType="ComissionRecordResult"> select sum(t.amount) as transferAmount, t.agentName as agentName, t.tillNumber as tillNumber, t.agentRealName as realName, count(*) as transactionNumber, sum(t.comission) as agentComissionAmount, sum(t.parentComission) as superAgentComissionAmount from comission_record t where 1=1 <if test="tillNumber != null and tillNumber != ''"> and t.tillNumber=#{tillNumber} </if> and t.parentTillNumber=#{supAgentTillNumber} and DATE_FORMAT( startTime, '%Y%m' ) = DATE_FORMAT(#{month} , '%Y%m' ) and t.status in (0) <if test="name != null and name != ''"> and t.agentName=#{name} or t.agentRealName=#{name} </if> group by agentName order by tillNumber desc </select>
沒問題代碼2
<select id="queryComissionRecord" resultType="ComissionRecordResult"> select sum(t.amount) as transferAmount, t.agentName as agentName, t.tillNumber as tillNumber, t.agentRealName as realName, count(*) as transactionNumber, sum(t.comission) as agentComissionAmount, sum(t.parentComission) as superAgentComissionAmount from comission_record t where 1=1 <if test="name != null and name != ''"> and (t.agentName=#{name} or t.agentRealName=#{name}) </if> <if test="tillNumber != null and tillNumber != ''"> and t.tillNumber=#{tillNumber} </if> and t.parentTillNumber=#{supAgentTillNumber} and DATE_FORMAT( startTime, '%Y%m' ) = DATE_FORMAT(#{month} , '%Y%m' ) and t.status in (0) group by agentName order by tillNumber desc </select>
兩份代碼的不同之處就在於,下划線部分的代碼的位置不一樣,如果放在前面,一旦name不為空的時候,條件開啟,or 就會把后面所有的條件都當成or的一部分。結果會有很大差異。
或者也可以和第三種一樣,括號優先一下。
在此小記一下,也幫助新手填坑吧。