我有这个声明:
select qulified_name
from table
inner join references_table on references_table.id = table.ref_id
where references_table.type = 'x' and table.value in (... +110 000 ids)
这是极其缓慢的。 (网络应用程序崩溃并且没有得到结果。 我在 rom-rb 的帮助下创建了我的声明,这使用了 sequel。但这是我在查看声明时得到的声明。
如果我像这样重写语句,与第一个版本相比性能真的很好:
select qulified_name
from table
inner join (select unnest(array['#{references_id.join("','")}']) id ) as tmp on tmp.id = businesspartner_references.value
inner join references_table on references_table.id = table.ref_id
where references_table.type = 'x'
这样我可以在大约 3 秒内得到结果。
有人可以向我解释为什么会这样吗?没看懂。。
最佳答案
当您使用 IN 子句时,尤其是有很多值时,数据库别无选择,只能迭代地将每个元组值与 IN 子句中的每个值进行比较,这将是低效的。
相反,当您使用子查询将它变成派生表时,它现在变成了一个面向集合的连接操作,相比之下。
数据库非常擅长评估面向集合的操作,并且可以为您的数据找到最佳的连接算法。
关于sql - 非常大的 IN (ids) 语句的性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42649632/