【发布时间】: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 种基本情况:
- @CustomerID 0 和 @ProductID 仅存在于 t1 中
- @CustomerID 0 和 @ProductID 存在于 t1 和 t2 中
- @CustomerID = 0 且 @ProductID 仅存在于 t1 中
- @CustomerID = 0 且@ProductID 存在于 t1 和 t2 中
上面的代码适用于案例 1-3,但在案例 4 中不返回任何内容。我认为这是因为最后一个 LEFT JOIN 中断(即使该 @ProductID 的数据在 t1 和 t2 中都存在)。
有没有办法在不使用 IF...ELSE 逻辑的情况下使第二个 LEFT JOIN 成为条件?
【问题讨论】:
标签: sql-server