SQL Server表加入问题

时间:2012-08-23 22:51:44

标签: sql-server-2005

我正在尝试连接三个表,我正在获取交叉行数据(获取6行而不是3行)。我尝试了内,左和右连接相同的结果。你能帮我吗?

表1

SELECT PATIENT,TDACTDATE,TDACTTIME,TDVALUE 
FROM NurDocumentedResults A 
WHERE (INTBASE = '400130') 
    AND (TDQUERY = 'NURPTVALUE') 
    AND (TDACTDATE = '20120425') 
AND TDVALUE >='8.0' AND A.PATIENT='F126' 

结果我得到了

F126    20120425    1715    8.8
F126    20120425    1840    8.4
F126    20120425    2300    9.7

表2

SELECT B.PATIENT,A.TESTRESULTDATE,A.TESTRESULTTIME,A.RESULT 
FROM LabLSpecResultTests A
INNER JOIN LabLSpecimenFile B 
    ON A.URN=B.URN 
    AND A.TESTRESULTDATE=B.COLLECTIONDATE 
WHERE A.TESTRESULTDATE='20120425' 
    AND (A.TEST IN ('100.0100', '100.0120', '100.0130', '100.0110')) 
    AND (A.RESULT > '8.0') 
    AND B.PATIENT='F126'

结果我得到了

F126    20120425    1756    8.5
F126    20120425    2335    9.2

当我加入所有三个表时,

SELECT D.PATIENT,TDACTDATE,TDACTTIME,TDVALUE,A.RESULT,A.RESULTTIME,A.TESTRESULTDATE,A.TESTRESULTTIME
FROM NurDocumentedResults D 
LEFT OUTER JOIN LabLSpecimenFile B 
    ON D.PATIENT=B.PATIENT AND D.TDACTDATE=B.COLLECTIONDATE
INNER JOIN LabLSpecResultTests A 
    ON A.URN=B.URN 
    AND A.TESTRESULTDATE=B.COLLECTIONDATE
WHERE (INTBASE = '400130') 
    AND (TDQUERY = 'NURPTVALUE') 
    AND (TDACTDATE = '20120425') 
    AND TDVALUE >='8.0' 
    AND A.TESTRESULTDATE='20120425' 
    AND  (A.TEST IN ('100.0100', '100.0120', '100.0130', '100.0110')) 
    AND (A.RESULT > '8.0') 
    AND D.PATIENT='F126'

我正在关注结果

F126    20120425    1715    8.8 8.5 2463    20120425    1756
F126    20120425    1840    8.4 8.5 2463    20120425    1756
F126    20120425    2300    9.7 8.5 2463    20120425    1756
F126    20120425    1715    8.8 9.2 22789   20120425    2335
F126    20120425    1840    8.4 9.2 22789   20120425    2335
F126    20120425    2300    9.7 9.2 22789   20120425    2335

1 个答案:

答案 0 :(得分:0)

建议:您可以从第一个表到连接其他两个的Select语句进行连接。很抱歉没有写实际查询 我在这台机器上没有sql来编写查询,因为我在linux上

尝试类似的东西 选择TableA。* 来自TableA LEFT JOIN(从表B中选择字段LEFT JOIN TABLEC在TableB ... = TableC)AS JOIN_TABLE ON TableA.Field = JOIN_TABLE.Field

尝试这样的事情,它可能会按你的意愿工作。