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

标签 mysql sql query-optimization

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

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/

相关文章:

mysql - 从 Excel 文件更新数据库表

mysql - 使用 RMySQL 连接到本地 MySQL 服务器

sql - MySQL慢查询

php - 针对多个 MYSQL 列查询 PHP 变量

SQL Server SELECT INTO @variable?

sqlite - SQLite 外键是否自动具有索引?

MySQL - 如何将具有多个相关子查询的查询优化为独立子查询?

mysql - max_allowed_pa​​cket 考虑了什么?

SQL Server 2014 - 模拟和 CTE 循环

mysql - 查询优化。没有 NOT IN 的查询