帮助优化子查询

时间:2010-11-07 04:44:17

标签: sql mysql optimization subquery

此查询提取与其他新闻文章类似地标记的新闻文章。有可能我可以消除其中一个我没有看到的子查询吗?

SELECT id, 
       title, 
       comment_count
  FROM NEWS
 WHERE (franchise_id = 1 OR franchise_id = 0)
   AND draft = 0
   AND id != 459
   AND id IN (SELECT news_id
                FROM news_tag_association
               WHERE tag_id IN (SELECT tag_id
                                  FROM news_tag_association
                                 WHERE news_id = 459))                               
 LIMIT 0, 5;

1 个答案:

答案 0 :(得分:2)

是的,没有GROUP BY或类似的,所以你可以使用普通的自联接:

SELECT
    id, title, comment_count
FROM news
JOIN news_tag_association n2t1 ON (news.id = n2t1.news_id)
JOIN news_tag_association n2t2 ON (n2t1.tag_id = n2t2.tag_id)
WHERE franchise_id IN (0, 1)
    AND draft = 0
    AND id != 459
    AND n2t2.news_id = 459
LIMIT 0,5;