gpt4 book ai didi

mysql - 需要帮助优化一个 sql 语句与几个 "field IN (subselect)"或在一起

转载 作者:太空宇宙 更新时间:2023-11-03 10:59:30 25 4
gpt4 key购买 nike

请建议如何最好地优化此查询。

select count(*)
from table1
where field1 in (select `text` from table2 where id=2)
or field2 in (select `text` from table2 where id=2)
or field3 in (select `text` from table2 where id=2);

我的第一个想法是将内部查询的结果选择为逗号分隔值,然后在 IN 子句中使用 csv 中的结果。但是有没有办法完全在 SQL 中执行此操作?

最佳答案

尝试转换为正确的联接并反转您的表顺序,以便您的 where id = 2 条件可以获得一些牵引力,并使用 union 拆分 OR 到可能允许使用索引的单独查询中:

select count(distinct id) from (
select t.id
from table2 t2
join table1 t on t.field1 = t2.`text`
where t2.id=2
union
select t.id
from grouplists t2
join table1 t on t.field2 = t2.`text`
where t2.id=2
union
select t.id
from grouplists t2
join table1 t on t.field3 = t2.`text`
where t2.id=2
)

您经常会发现单独的查询优于基于单个“或”的查询,因为“或”的每个部分都可以使用自己的(最佳)索引。

关于mysql - 需要帮助优化一个 sql 语句与几个 "field IN (subselect)"或在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17046484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com