使用 MyBatis <foreach> 搭配 #{item.property} 進行 Oracle 多條件批量刪除,SQL 語法正確、參數日誌無誤,但資料庫執行計畫顯示未命中索引、實際未刪除任何資料。
#{ } 會生成 PreparedStatement 佔位符 (?),Oracle 在解析含大量 OR 條件的 SQL 時,可能無法正確推導執行計畫,導致全表掃描或參數綁定失效。
<delete id="delMultiByIds2" parameterType="java.util.List">
delete from tb_duty A where exists (
select 1 from (
<foreach collection="list" item="item" separator="union all">
select * from tb_duty B
where 1=1
and B.dscd=${item.dscd}
and B.unit_id=${item.unitId}
and B.year=${item.year}
and B.month=${item.month}
and B.flag=${item.flag}
</foreach>
) S where A.duty_id = S.duty_id
)
</delete>
IN 或 OR 列表,利用集合運算提升效率。Oracle 大量資料多條件批量刪除/更新,且需確保索引生效時。MySQL/PostgreSQL 通常 #{ } 即可正常工作。