SQL连接查询 - 首先选择特定条目,否则选择NULL

时间:2012-09-19 12:30:43

标签: sql join

我确定之前已经回答过,但我找不到它!

表 - 预订B

Customer    Product
Tim         Milk
Bob         Milk

表 - 产品P

Customer    Product     Description
Tim         Milk         This is Tim's Milk
NULL        Milk         This is Anybody's Milk

我想加入表并获得以下输出(为简单起见,在示例中显示所有列):

B.Customer    B.Product   P.Customer     P.Product    P.Description
Tim           MILK        Tim            MILK         This is Tim's Milk
Bob           MILK        NULL           MILK         This is Anybody's Milk

因此,查询应首先查找是否存在特定的客户相关产品,如果是,请使用它,否则使用通用产品......

非常感谢!

2 个答案:

答案 0 :(得分:2)

   SELECT B.Customer, B.Product,
          ISNULL(C.Customer,P.Customer) Customer,
          CASE WHEN C.Customer IS NULL THEN P.Description
               ELSE C.Description END Description
     FROM B
LEFT JOIN C ON C.Product = B.Product and C.Customer = B.Customer
LEFT JOIN P ON P.Product = B.Product and P.Customer IS NULL

答案 1 :(得分:0)

我想我们需要加入两次:首先是客户和产品,然后是产品

SELECT
  B.Customer,
  B.Product,
  IFNULL(Pfound.Customer,PnotFound.Customer) AS P_Customer,
  IFNULL(Pfound.Product,PnotFound.Product) AS P_Product,
  IFNULL(Pfound.Description,PnotFound.Description) AS P_Description
FROM B
  LEFT JOIN P AS Pfound
    ON B.Customer=Pfound.Customer
    AND B.Product=Pfound.Product
  LEFT JOIN P AS PnotFound
    ON B.Product=PnotFound.Product
    AND PnotFound.Customer IS NULL