解决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
)
相关推荐
不羁。。6 小时前
【撸靶笔记】第八关:GET - Blind - Boolian Based - Single Quotes
数据库·sql·mybatis
AwhiteV7 小时前
利用图数据库高效解决 Text2sql 任务中表结构复杂时占用过多大模型上下文的问题
数据库·人工智能·自然语言处理·oracle·大模型·text2sql
m0_595199857 小时前
Redis(以Django为例,含具体操作步骤)
数据库·redis·缓存
爱尚你19937 小时前
MySQL 三大日志:redo log、undo log、binlog 详解
数据库·mysql
小猿姐9 小时前
KubeBlocks AI:AI时代的云原生数据库运维探索
数据库·人工智能·云原生·kubeblocks
NocoBase10 小时前
10 个开源工具,快速构建数据应用
数据库·低代码·开源
麻辣清汤11 小时前
结合BI多维度异常分析(日期-> 商家/渠道->日期(商家/渠道))
数据库·python·sql·finebi
钢铁男儿11 小时前
Python 正则表达式(正则表达式和Python 语言)
python·mysql·正则表达式
Kan先生12 小时前
对象存储解决方案:MinIO 的架构与代码实战
数据库·python
超级迅猛龙12 小时前
保姆级Debezium抽取SQL Server同步kafka
数据库·hadoop·mysql·sqlserver·kafka·linq·cdc