2017-02-21 8 views
2

Ich versuche, 3 Tabellen LEFT JOIN wie so:Wie erstelle ich einen bedingten LEFT JOIN?

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) 

Es gibt 4 grundlegende Fälle Ich versuche zu lösen:

  1. <> 0 und @ProductID existiert @CustomerID in t1 nur
  2. @CustomerID <> 0 und @ProductID existiert in T1 und t2
  3. @CustomerID = 0 und @ProductID existiert in t1 nur
  4. @ CustomerID = 0 und @ProductID existiert in T1 und T2

Der obige Code für Fälle funktioniert 1-3, gibt aber nichts für den Fall, 4. Ich denke, es ist, weil das letzte LEFT JOIN Pausen (obwohl Daten in beide vorhanden t1 und t2 für diese @ProductID).

Gibt es eine Möglichkeit, den zweiten LINKEN JOIN ohne IF ... ELSE-Logik bedingungsabhängig zu machen?

Antwort

1

die Bedingungen in der on Klausel Setzen Sie anstelle der where Klausel

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 
+0

Danke, das tat es! –

0

Wenn ich verstehe, was Sie wollen, dies funktionieren könnte:

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