sql查詢rownum下標不對導致結果不正確

最近碰到個問題:頁面表格中的實際展示數量和頁腳展示的數量不一致,通過日誌發現sql語句中的一個參數錯誤,但是debug時,參數卻是正確的,只是到sql執行時參數變了。經過仔細尋找,終於發現問題所在,先看sql:

SELECT * FROM
(SELECT B.*, ROWNUM RN FROM
(SELECT *
FROM tableName1 u
LEFT JOIN tableName2 ur
ON u.id= ur.id
AND ur.code= #{code, jdbcType=VARCHAR}
<where>
<if test="codes != null and codes.size() > 0 ">
AND u.code IN
<foreach collection="codes" item="code" index="index" open="(" separator="," close=")">
#{code}
</foreach>
</if>
<if test="status != null and status !='' ">
AND u.STATUS = #{status, jdbcType=VARCHAR}
</if>
</where>
) B
WHERE rownum &lt; = #{offset} )
WHERE RN &gt; #{index}

原因即爲兩個參數相同了,第一個index會隨着codes的size而變化,覆蓋掉了java代碼中傳過來的固定的index的值,導致最後查詢結果數量不對。

將第一個紅色的index改成其他的參數即可,例如:

SELECT * FROM
(SELECT B.*, ROWNUM RN FROM
(SELECT *
FROM tableName1 u
LEFT JOIN tableName2 ur
ON u.id= ur.id
AND ur.code= #{code, jdbcType=VARCHAR}
<where>
<if test="codes != null and codes.size() > 0 ">
AND u.code IN
<foreach collection="codes" item="code" index="cursor" open="(" separator="," close=")">
#{code}
</foreach>
</if>
<if test="status != null and status !='' ">
AND u.STATUS = #{status, jdbcType=VARCHAR}
</if>
</where>
) B
WHERE rownum &lt; = #{offset} )
WHERE RN &gt; #{index}

後續開發寫sql時,一定要注意參數的命名,給自己長個記性。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章