如何在SQL中相互依赖地联接五个表

时间:2018-09-05 15:38:55

标签: sql-server

我想在SQL Server中加入五个表。顺序如下。逻辑应该是 Table1 >>>>键:ID >>>> Table_A和Table_B(如果Table1.Status = ABC,则Table_A否则为Table_B)>>>键:NUMBER >>> Table2 >>>键:Number + Item_No >>> Table3 < / p>

如果以下代码可以工作,请提供帮助。

enter image description here

SELECT * FROM 
TABLE1
LEFT JOIN (CASE WHEN status = 'ABC' THEN Table_A ELSE Table_B END ) X ON (Table1.ID = X.ID)
LEFT JOIN Table2 ON (X.NUMBER = Table2.NUMBER)
LEFT JOIN Table3 ON (Table3.CONCAT(NUMBER + Item_No) = Table2.CONCAT(NUMBER + Item_No))

1 个答案:

答案 0 :(得分:2)

SELECT Q.*, T2.ItemNo, T2.Product, T3.Connection
FROM (
     SELECT T1.ID, CASE WHEN T1.Status = 'ABC'
                        THEN TA.Number
                        ELSE TB.Number
                   END as Number
     FROM Table1 T1
     LEFT JOIN TableA TA
       ON T1.ID = TA.ID
     LEFT JOIN TableB TB
       ON T1.ID = TB.ID
     ) as Q
JOIN Table2 T2
  ON Q.Number = T2.Number
JOIN Table3 T3
  ON T2.ItemNo = T3.ItemNo