我无法理解简单 MySQL 查询中的问题。请看这里
select SQL_NO_CACHE
ID,
post_title,
post_type
from wp_posts
where 1
and (wp_posts.ID in (select id from ...[complex subquery here]...))
这个查询运行相当长(2.5秒),但是如果我单独运行子查询(来自“in(..”)的子查询只需要0.15秒。子查询只返回60行,我认为整个查询有在这种情况下跑得更快。
顺便说一句,我尝试使用固定 ID 列表而不是子查询来运行整个查询,例如
select SQL_NO_CACHE
ID,
post_title,
post_type
from wp_posts
where 1
and (wp_posts.ID in
(
48393,
52796, .... 58 more numbers))
而且它的工作速度非常快(~1 毫秒)。
问题出在哪里?为什么整个查询运行如此慢以及如何改进?谢谢。
最佳答案
如上所述,mysql 在这种情况下并不擅长优化查询。可能发生的情况是它对 wp_posts 中的每条记录执行一次子查询。通过使用联接将它们组合成单个查询来避免这种行为
select SQL_NO_CACHE
ID,
post_title,
post_type
from wp_posts
left join another_table on wp_posts.id = another_table.post_id
where {complex conditions from your other query}
希望这对您有帮助
关于Mysql长子查询 "in"问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31277324/