【问题标题】:How do I create a conditional LEFT JOIN?如何创建有条件的 LEFT JOIN?
【发布时间】:2017-02-21 15:53:31
【问题描述】:

我正在尝试像这样 LEFT JOIN 3 个表:

DECLARE @CustomerID AS INT;
DECLARE @ProductID AS INT;

SELECT *
FROM table1 t1
    LEFT JOIN table2 t2 ON t1.id = t2.id
    LEFT JOIN table3 t3 ON t2.loc = t3.loc
WHERE t1.id = @ProductID
    AND (t2.loc = t3.loc OR t2.loc IS NULL)
    AND (t3.cid = @CustomerID OR t3.cid IS NULL)

我正在尝试解决 4 种基本情况:

  1. @CustomerID 0 和 @ProductID 仅存在于 t1 中
  2. @CustomerID 0 和 @ProductID 存在于 t1 和 t2 中
  3. @CustomerID = 0 且 @ProductID 仅存在于 t1 中
  4. @CustomerID = 0 且@ProductID 存在于 t1 和 t2 中

上面的代码适用于案例 1-3,但在案例 4 中不返回任何内容。我认为这是因为最后一个 LEFT JOIN 中断(即使该 @ProductID 的数据在 t1 和 t2 中都存在)。

有没有办法在不使用 IF...ELSE 逻辑的情况下使第二个 LEFT JOIN 成为条件?

【问题讨论】:

    标签: sql-server


    【解决方案1】:

    将条件放在on 子句中,而不是where 子句中

    SELECT *
    FROM table1 t1
        LEFT JOIN table2 t2 ON t1.id = t2.id
        LEFT JOIN table3 t3 ON t2.loc = t3.loc
                           AND (t3.cid = @CustomerID OR t3.cid IS NULL)
                           AND (t2.loc = t3.loc OR t2.loc IS NULL)
    WHERE t1.id = @ProductID
    

    【讨论】:

    • 谢谢,成功了!
    【解决方案2】:

    如果我明白你想要什么,这可能会奏效:

    SELECT * FROM table1 a
        LEFT JOIN table2 b 
          ON b.id = a.id
        LEFT JOIN table3 c 
          ON c.loc = b.loc
             and isNull(c.cid, @CustomerID) = CustomerID 
    WHERE t1.id = @ProductID
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-22
      • 2021-08-23
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 2020-08-24
      • 2014-03-13
      相关资源
      最近更新 更多