【问题标题】:SQL query all products including those without descriptionsSQL查询所有产品,包括没有描述的产品
【发布时间】:2013-06-30 06:17:35
【问题描述】:

我有以下查询从多个表中获取产品 ID、产品名称、价格、描述和成分。

SELECT TP.intProductID AS ProductID, TP.strName AS Name, TPP.decPrice AS Price,
TD.strDescription AS Description, GROUP_CONCAT( TRH.strName     SEPARATOR ', ' ) AS Ingredients 
FROM TProducts TP JOIN

     TProductsPrices TPP 
     on TP.intProductID=TPP.intProductID JOIN

     TProductsDescriptions TPD 
     on TP.intProductID=TPD.intProductID JOIN

     TDescriptions TD
     on TPD.intDescriptionID=TD.intDescriptionID JOIN

     TProductsIngredients TPI
     on TPD.intProductID=TPI.intProductID JOIN

     TRawHerbs TRH
     on TPI.intIngredientID=TRH.intRawHerbID

GROUP BY TPD.intProductID;

查询以应有的方式查找所有产品信息,但我希望能够在我的结果中包含描述表中没有描述的产品(并且可能返回 null 或空字符串)。我怎么能做这样的事?

【问题讨论】:

    标签: sql join conditional-statements


    【解决方案1】:

    将适用的内连接更改为左外连接。像这样的:

    SELECT TP.intProductID AS ProductID, TP.strName AS Name, TPP.decPrice AS Price,
    TD.strDescription AS Description, 
    GROUP_CONCAT( TRH.strName     SEPARATOR ', ' ) AS Ingredients 
    FROM TProducts TP JOIN
    
     TProductsPrices TPP 
     on TP.intProductID=TPP.intProductID 
    
    left JOIN TProductsDescriptions TPD 
     on TP.intProductID=TPD.intProductID 
    
    left JOIN TDescriptions TD
     on TPD.intDescriptionID=TD.intDescriptionID 
    
    JOIN TProductsIngredients TPI
     on TPD.intProductID=TPI.intProductID 
    
    JOIN TRawHerbs TRH
     on TPI.intIngredientID=TRH.intRawHerbID
    
    GROUP BY TPD.intProductID;
    

    【讨论】:

    • 好的,我是新加入的,我尝试在指定位置添加 LEFT 关键字,但查询仍然排除没有描述的产品
    【解决方案2】:

    您以一种典型的方式构建了查询,其中您有一个产品表,然后从中导入内容。要将所有内容保留在产品表中,所有联接都应为left outer joins。此外,productId 上的连接应该回到原始表:

    SELECT TP.intProductID AS ProductID, TP.strName AS Name, TPP.decPrice AS Price,
           TD.strDescription AS Description,
           GROUP_CONCAT( TRH.strName     SEPARATOR ', ' ) AS Ingredients 
    FROM TProducts TP left outer JOIN
         TProductsPrices TPP 
         on TP.intProductID=TPP.intProductID left outer JOIN
         TProductsDescriptions TPD 
         on TP.intProductID=TPD.intProductID left outer JOIN
         TDescriptions TD
         on TPD.intDescriptionID=TD.intDescriptionID left outer JOIN
         TProductsIngredients TPI
         on TP.intProductID=TPI.intProductID left outer JOIN
         TRawHerbs TRH
         on TPI.intIngredientID=TRH.intRawHerbID
    GROUP BY TPD.intProductID;
    

    这将保留TProducts 中的所有产品,无论它们在其他表中是否有匹配项。

    一般来说(特别是如果您正在学习联接),我建议您在 from 子句中坚持使用一种类型的 join。这种结构,其中所有内容都是left outer join,表示“将所有内容保留在第一个表中”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-16
      • 2020-10-21
      • 2019-07-29
      • 1970-01-01
      • 1970-01-01
      • 2022-06-22
      • 1970-01-01
      相关资源
      最近更新 更多