编码技巧——批量删除数据

1. 背景

今天遇到个业务场景需要批量根据索引删除数据,ORM框架为mybatis,跟以往遇到的根据MySQL主键批量删除不同,本次使用的数据库时PgSQL,使用的联合主键索引;搜索相关资料网上大部分帖子都是使用类似 where id in (...) 的写法,直到找到花了点时间才找到合适的写法,现在总结下;

2. 代码

(1)对于单列主键一般使用IN语句

XML 复制代码
    <delete id="batchDelByIds" parameterType="list">
        delete
        from t_data
        where id in
        <foreach collection="list" item="batchId" index="index" open="(" close=")" separator=",">
            #{batchId}
        </foreach>
    </delete>

(2)使用OR语句连接多个条件

XML 复制代码
    <delete id="batchDelByNameAgeEntrys" parameterType="list">
        delete
        from t_data
        where
        <foreach collection="list" item="item" index="index" separator=" or ">
            (`name`={#item.name,VARCHAR} and `age`={#item.age,INTEGER})
        </foreach>
    </delete>

(3)使用多条DELETE语句执行

XML 复制代码
    <delete id="batchDelByNameAgeEntrysV2" parameterType="list">
        <foreach collection="list" item="item" index="index" separator=";">
            delete
            from t_data
            where
            `name`={#item.name,VARCHAR} and `age`={#item.age,INTEGER}
        </foreach>
    </delete>

注意,这种写法需要sql连接支持多条语句执行,需要在jdbc.url上加上多语句命令的参数,例如:

Lua 复制代码
spring.datasource.url=jdbc:mysql://127.0.0.1:11070/test?useUnicode=true&amp;characterEncoding=UTF-8&amp;allowMultiQueries=true

(4)使用多参数的IN语句

XML 复制代码
    <delete id="batchDelByIds" parameterType="list">
        delete
        from t_data
        where (`name`, `age`) in
        <foreach collection="list" item="item" index="index" open="(" close=")" separator=",">
            ({#item.name,VARCHAR}, {#item.age,INTEGER})
        </foreach>
    </delete>

本次的场景就适合这种写法;注意,如果多字段非联合索引,建议新建联合索引;

以上,希望你能帮到你;

相关推荐
码农-0041 天前
Springboot 集成 Ehcache操作数据库显示SQL语句设置
数据库·spring boot·sql
钱栈up1 天前
全量 21 个失败、单跑全绿:泄漏进连接池的 SQL 变量
sql·单元测试·测试
大漠孤烟s1 天前
7.mybatisplus学习-条件构造器、插件、通用枚举、多数据源环境、MybatisX
mybatis
旺仔不是程序员1 天前
pg_trgm GIN 索引:PostgreSQL 正则、模糊与近似度查询的三合一加速器
数据库·后端·sql
ee又momo1 天前
MyBatis-Plus 用了就回不去,这些功能真香
mybatis
考虑考虑1 天前
SQL中的 CASE WHEN
数据库·后端·sql
旺仔不是程序员1 天前
索引膨胀与重建:PostgreSQL REINDEX 生产实践
数据库·后端·sql
漂着的圆木7 天前
Agent 功能参与度:Copilot 怎么算
sql·数据分析·agent·githubcopilot·度量
旺仔不是程序员7 天前
LIMIT 1:PostgreSQL 只取一行的高效查询姿势
数据库·后端·sql