我有一个简单的查询,有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
可能会出现3个表格。由于我的SQL有点弱,我将非常感谢为此提供适当的解决方案。
答案 0 :(得分: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查询指定连接...你没有提供关于sub如何有那么多的线索 - 应该构建查询。