Mysql,嵌套EXISTS语句的正确方法是什么

时间:2013-12-15 02:31:02

标签: mysql

我正在尝试将EXISTS语句放在EXISTS语句中,我的版本无效。 有可能吗?

SELECT SUM(nbview) AS num_rows 
FROM `Release_link` 
WHERE EXISTS (SELECT id 
                 FROM Release 
                 WHERE Release.id = Release_link.release_id 
                   AND EXISTS (SELECT id 
                                 FROM Article 
                                WHERE Article.id = Release.article_id 
                                  AND Article.type = 'lol'));

感谢Jorge Campo的解决方案;)forg0t引用一些东西;)

1 个答案:

答案 0 :(得分:0)

问题是您在第一个Release_link上引用select并且未在第一个子选择中引用它。你可以引用两者,也可以不引用。

SELECT SUM(nbview) AS num_rows 
  FROM `Release_link` 
 WHERE EXISTS (SELECT id 
                 FROM Release 
                 WHERE Release.id = `Release_link`.release_id 
                   AND EXISTS (SELECT id 
                                 FROM Article 
                                WHERE Article.id = Release.article_id 
                                  AND Article.type = 'lol'));

或者

SELECT SUM(nbview) AS num_rows 
  FROM Release_link 
 WHERE EXISTS (SELECT id 
                 FROM Release 
                 WHERE Release.id = Release_link.release_id 
                   AND EXISTS (SELECT id 
                                 FROM Article 
                                WHERE Article.id = Release.article_id 
                                  AND Article.type = 'lol'));

对于性能问题,在这种特定情况下,更喜欢使用INNER JOIN操作。 Mysql引擎可以更好地处理索引(假设这些ID字段上有索引。)

SELECT SUM(Release_link.nbview) AS num_rows 
  FROM Release_link 
       INNER JOIN Release
          ON (Release.id = Release_link.release_id)
       INNER JOIN Article
          ON (Article.id = Release.article_id)
 WHERE Article.type = 'lol';