解决sql查询中in查询项过多时很慢的问题

最近遇到查询一张大数据量表时,需要对一个字段做in查询,in中的元素数量可能达到几千个,即使对这个字段加上索引,速度也慢到无法接受

示例表结构如下:

表中有几十万的数据,且example_id和data_id字段加了联合索引,只做一个简单的select查询:

sql 复制代码
select * from TEST_TABLE01 where example_id=:exampleId and data_id in(:dataIds)

其中in存在1000个元素,查询速度很慢,因为in的个数太多,会全表扫描,导致索引失效。

优化方案:

不使用in语法,将sql语句简化成下面这种,索引就生效了

sql 复制代码
select * from TEST_TABLE01 where example_id=:exampleId and data_id=:dataId

但是这样一次只能查询一条data_id匹配的数据,这就意味着程序要和数据库交互1000次,但是我测试的速度要快于上面的in方式。

进一步优化,减少数据库交互方式,使用union all拼接sql:

sql 复制代码
select * from TEST_TABLE01 where example_id=:exampleId and data_id=:dataId0
union all
select * from TEST_TABLE01 where example_id=:exampleId and data_id=:dataId1
union all
select * from TEST_TABLE01 where example_id=:exampleId and data_id=:dataId2
union all
select * from TEST_TABLE01 where example_id=:exampleId and data_id=:dataId3
...
...
union all
select * from TEST_TABLE01 where example_id=:exampleId and data_id=:dataId999

程序中对dataId的参数进行组装,这样只和数据库交互一次,索引也不会失效,这种方式解决了in查询慢的问题。

对于delete也可以使用类似的方式优化:

sql 复制代码
delete from TEST_TABLE01 a
WHERE exists (
    select * from (
        select * TEST_TABLE01 where example_id=:exampleId and data_id=:dataId0
        union all
        select * TEST_TABLE01 where example_id=:exampleId and data_id=:dataId1
    ) b where a.id=b.id
)
相关推荐
逍遥德41 分钟前
PostgreSQL 中唯一约束(UNIQUE CONSTRAINT) 和唯一索引(UNIQUE INDEX) 的核心区别
数据库·sql·postgresql·dba
工业甲酰苯胺44 分钟前
字符串分割并展开成表格的SQL实现方法
数据库·sql
科技块儿1 小时前
IP定位技术:游戏反外挂体系中的精准识别引擎
数据库·tcp/ip·游戏
衫水1 小时前
[特殊字符] MySQL 常用指令大全
数据库·mysql·oracle
卓怡学长1 小时前
m115乐购游戏商城系统
java·前端·数据库·spring boot·spring·游戏
小句2 小时前
SQL中JOIN语法详解 GROUP BY语法详解
数据库·sql
阿杰 AJie3 小时前
MySQL 里给表添加索引
数据库·mysql
昊昊该干饭了3 小时前
一个真实查询需求如何从表设计走到高效 SQL
数据库·sql
Ha_To4 小时前
2026.1.20 SQL Server命令
数据库
智在碧得4 小时前
碧服打造DataOps全链路闭环,定义大数据工程化发布新标杆
大数据·网络·数据库