SQL Multiple Joins无法按预期工作

时间:2017-08-04 19:23:49

标签: sql sql-server join query-optimization jointable

当我尝试加入所有4个表时,我有以下查询无效(运行需要一个多小时,我必须最终终止查询而不返回任何数据)。 它在表1,2和表1中有效。 3加入AND然后如果我尝试表1,2& 4加入但不是当我尝试加入下面的所有4个表时。

Select * From
    (Select 
        R.ID, R.MId, R.RId, R.F_Name, R.F_Value, FE.FullEval, M.Name, RC.CC     
        FROM Table1 as R
        Inner Join Table2 FE
                ON R.ID = FE.RClId and R.MId = FE.MId and R.RId = FE.RId
            Inner Join Table3 as M
                 ON R.MId = M.MId and FE.MId = M.MId
               Inner Join Table4 as RC
                  ON R.RId = RC.RId and FE.RId = RC.RId and FE.Date = RC.Date

    ) AS a

注意: 1)表3中没有RId。 2)表4中没有MId。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

由于您提到您没有权限查看查询计划,请尝试分解每个表连接。您还可以检查哪个表连接花费时间来检索记录。从那里,您可以调查数据为何需要时间。可能是因为表3和表4中没有列密钥?

WITH Tab1_2 AS
(SELECT r.ID, r.MId, r.RId, r.F_Name, r.F_Value, fe.FullEval, fe.date
   FROM Table1 as r
  INNER JOIN Table2 fe
     ON r.ID = fe.RClId
    AND r.MId = fe.MId
    AND r.RId = fe.RId
  WHERE ... -- place your conditions if any
),

Tab12_3 AS
(SELECT t12.*, m.Name
   FROM Tab1_2 t12
  INNER JOIN Table3 as m
     ON t12.MId = m.MId
  WHERE ... -- place your conditions if any
),

Tab123_4 AS
(SELECT t123.ID, t123.MId, t123.RId, t123.F_Name, t123.F_Value, t123.FullEval, rc.CC
   FROM Tab12_3 t123
  INNER JOIN Table4 as rc
     ON t123.RId = rc.RId 
    AND t123.Date = rc.Date
  WHERE ... -- place your conditions if any
)

SELECT *
  FROM Tab123_4 t1234