为什么这个左连接不显示左边的表中与右表不匹配的所有数据? (MySQL的)

时间:2011-11-02 15:55:13

标签: mysql join left-join

我有以下查询应该选择Articles_New中的所有文章,这些文章是A)不在ArticlesInCategories_New或B)中,但没有CategoryID = 7,8,9,10或11 。

通过删除Category!=行,我确定问题是(至少)Articles_New没有选择Articles_New中不属于ArticlesInCategories_New的所有内容。我仍然不太了解GroupBy,但我基于其他问题,我尝试了GroupBy Articles_New.ArticleID,并没有改变任何东西。

    SELECT 
       DISTINCT Articles_New.ArticleID, 
       DATE_FORMAT(Articles_New.PublicationDate, '%c/%e/%Y') AS ReleaseDate, 
       Articles_New.Title, 
       Articles_New.Type, 
       Articles_New.URL
     FROM 
       Articles_New
        LEFT JOIN ArticlesInCategories_New
            ON ArticlesInCategories_New.ArticleID = Articles_New.ArticleID
     WHERE 
       PublicationDate >= DATE_SUB(CURDATE(), INTERVAL 2 MONTH) AND
       PublicationDate <= CURDATE() AND
       Articles_New.Public = '1'
       AND ArticlesInCategories_New.CategoryID != '7'
       AND ArticlesInCategories_New.CategoryID != '8'
       AND ArticlesInCategories_New.CategoryID != '9'
       AND ArticlesInCategories_New.CategoryID != '10'
       AND ArticlesInCategories_New.CategoryID != '11' 
     ORDER BY 
       Articles_New.PublicationDate DESC,
       Articles_New.ArticleID DESC

2 个答案:

答案 0 :(得分:2)

您希望的所有行
A)不在ArticlesInCategories_New中 B)在ArticlesInCategories_New中,但没有CategoryID = 7,8,9,10或11。

SELECT DISTINCT 
   Articles_New.ArticleID, 
   DATE_FORMAT(Articles_New.PublicationDate, '%c/%e/%Y') AS ReleaseDate, 
   Articles_New.Title, 
   Articles_New.Type, 
   Articles_New.URL
 FROM 
   Articles_New
    LEFT JOIN ArticlesInCategories_New
        ON ArticlesInCategories_New.ArticleID = Articles_New.ArticleID
 WHERE 
   (
     ArticlesInCategories_New.ArticleID IS NOT NULL AND
     PublicationDate BETWEEN DATE_SUB(CURDATE(), INTERVAL 2 MONTH) AND CURDATE()
     AND Articles_New.Public = '1'
     AND ArticlesInCategories_New.CategoryID NOT IN ('7','8','9','10','11')
   )
   OR 
   (
     ArticlesInCategories_New.ArticleID IS NULL
   )
 ORDER BY 
   Articles_New.PublicationDate DESC,
   Articles_New.ArticleID DESC

答案 1 :(得分:1)

您描述了两组您想要的文章 - all the articles from Articles_New,它们满足以下条件之一:

  • A)不在ArticlesInCategories_New
  • B)在ArticlesInCategories_New中,但没有CategoryID = 7,8,9,10或11。

您可以通过分别查找这两个集合,然后将它们与UNION组合来简化此复杂查询。这将允许您单独测试和调试每个查询。