以下使用双嵌套子查询的mysql查询太慢
SELECT t.name
FROM creatives AS c
INNER JOIN term_relationships AS tr ON tr.creative_id=c.creative_id
INNER JOIN terms AS t ON t.term_id=tr.term_id
WHERE c.creative_id IN
(SELECT creative_id
FROM term_relationships
WHERE term_id IN
(SELECT offer_term_id
FROM offer_urls))
AND t.taxonomy LIKE 'ad_network';
内部查询
SELECT creative_id
FROM term_relationships
WHERE term_id IN
(SELECT offer_term_id
FROM offer_urls)
非常快(0.04秒)
但完整查询并未提供结果。等了大约5分钟后我放弃了。
有什么办法优化这个?
答案 0 :(得分:2)
尝试:
SELECT t.name
FROM creatives AS c
JOIN term_relationships AS tr ON tr.creative_id=c.creative_id
JOIN terms AS t ON t.term_id=tr.term_id
JOIN term_relationships tr2 ON tr2.creative_id = c.creative_id
JOIN offer_urls ou ON ou.offer_term_id = tr2.term_id
WHERE t.taxonomy LIKE 'ad_network';
这个只用JOIN编写的版本会更快。
答案 1 :(得分:0)
尝试使用exists
:
SELECT t.name
FROM terms t JOIN
term_relationships tr
ON t.term_id = tr.term_id JOIN
creatives c
ON tr.creative_id = c.creative_id
WHERE EXISTS (SELECT 1
FROM term_relationships tr2 JOIN
offer_urls ou
ON tr.term_id = ou.offer_term_id
WHERE c.creative_id = tr2.creative_id
) AND
t.taxonomy LIKE 'ad_network';
然后为此您需要以下索引:
您可能已经使用主键定义定义了其中一些。