0

我有一个包含 4 个表的简单查询。它工作正常,现在我需要在该查询中再添加一个连接,但是这次表根据该查询中的一个参数而变化;

我的查询如下所示:

SELECT pat.Id,dgroup.Diagnosis as 'Description', ntest.Testname as 'TestName',
       dgroup.Id as 'ProrityId', subt.TestSubType, **ntest.SubGroupId**
  from pat.tbl_PatientTestRecord pat
          JOIN tbl_Test_DiagnosisGroup InTest on pat.IndividualTestId=InTest.Id
          JOIN tbl_NrlTests nTest ON InTest.TestId=nTest.id
          JOIN tbl_DiagnosisGroup dgroup ON Intest.DGId=dgroup.id
          Left Join 
             **tbl_vary**
  • tbl_vary取决于ntest.subgroupID。并且可能有 3 个表可能出现在tbl_vary.

由于我的 SQL 有点弱,我将非常感谢为此提供适当的解决方案。

4

1 回答 1

1

一种可能性是 UNION 子查询:

SELECT pat.Id,dgroup.Diagnosis as 'Description', ntest.Testname as 'TestName',
       dgroup.Id as 'ProrityId', subt.TestSubType, **ntest.SubGroupId**
  FROM pat.tbl_PatientTestRecord pat
  JOIN tbl_Test_DiagnosisGroup InTest on pat.IndividualTestId=InTest.Id
  JOIN tbl_NrlTests nTest ON InTest.TestId=nTest.id
  JOIN tbl_DiagnosisGroup dgroup ON Intest.DGId=dgroup.id
  LEFT JOIN
       (SELECT v1.SubGroupId, v1.Relevant_Col_1 AS rc1, v1.Relevant_Col_2 AS rc2
          FROM table_variant_1 AS v1
         WHERE v1.SubGroupId = ntest.SubGroupID
        UNION
        SELECT v2.SubGroupId, v2.Alternative_1 AS rc1, v2.Alternative_2 AS rc2
          FROM table_variant_2 AS v2
         WHERE v2.SubGroupId = ntest.SubGroupID
        UNION
        SELECT v3.SubGroupId, v3.Other_Source_1 AS rc1, v3.Other_Source_2 AS rc2
          FROM table_variant_3 AS v3
         WHERE v3.SubGroupId = ntest.SubGroupID
       ) AS u
    ON u.SubGroupId = ntest.SubGroupId

如果在子查询中没有 WHERE 子句,您可能会更好,或者可能有其他方法可以使用 UNION 查询指定连接……您还没有提供关于子查询应该如何使用的所有线索被建造。

于 2013-06-16T05:35:35.890 回答