代码之家  ›  专栏  ›  技术社区  ›  I'm here for Winter Hats

在“除外”之前或之后联接表

  •  2
  • I'm here for Winter Hats  · 技术社区  · 9 年前

    我有两个数据表,上表是产品,下表是类别。

    enter image description here

    在products表中,我有一些产品并不是每个categoryID都有,比如3和7。我通过使用此语句发现了这一点。

    Select CategoryID
    From Categories 
    Except
    Select CategoryID
    From Products
    

    这就产生了这个结果

    enter image description here

    我想将categoryName和描述包含在我的上述查询中。我可以接受这个查询并将一个表连接到它上以获得预期的输出吗?如果没有,我如何使用 Outer Join 为了实现我的最终结果,而不是 Except ?

    3 回复  |  直到 9 年前
        1
  •  3
  •   Tim Biegeleisen    9 年前

    我不知道您使用什么数据库来生成显示给我们的结果,因为AFAIK MySQL不支持 EXCEPT .但你的问题是可以回答的;你可以做 LEFT JOIN 在两个表之间获得相同的结果:

    SELECT t1.CategoryID
    FROM Categories t1
    LEFT JOIN Products t2
        ON t1.CategoryID = t2.CategoryID
    WHERE t2.CategoryID IS NULL       -- NULL indicates the Categories record did not match
    
        2
  •  2
  •   SHADOWSONIC    9 年前

    在SQL中,您可以使用它。但这只是显示ID仅在类别表中。它不显示在产品表中

    Select categoryName, Description
    From Products
    where id = ( Select CategoryID
                 From Categories 
                 Except
                 Select CategoryID
                 From Products )
    
        3
  •  0
  •   Fruchtzwerg    9 年前
    SELECT CategoryID,CategoryName,Description
    FROM Categories t1
    where CategoryId not in(select p.CategoryID from Products p)