我有3张桌子。一个表格中包含所有人[Pat]
,每个人都有一个唯一的[PatId]
。第二个表包含保险公司的所有信息[Ins]
,每个信息都有唯一的[InsId]
。第三个表格包含患者保险信息[PatIns]
。在[PatIns]
表中,一些患者(也[PatId]
)有第二或第三保险,并在[InsType]
中表示为1,2或3.我需要一个SQL查询,不仅加入3个表,但当患者有第二或第三保险时也返回数据。到目前为止,我有:
SELECT *
FROM [XEREX_TEST].[dbo].[xrxPat],
[XEREX_TEST].[dbo].[xrxIns],
[XEREX_TEST].[dbo].[xrxPatIns]
[XEREX_TEST].[dbo].[xrxPatIns] AS INS2,
[XEREX_TEST].[dbo].[xrxPatIns] AS INS3
WHERE [xrxPat].[PatId]=[xrxPatIns].[PatId]
AND [xrxPatIns].[PatId] = INS2.[PatId]
AND [xrxPatIns].[PatId] = INS3.[PatId]
AND [xrxIns].[RecNo]=[xrxPatIns].[InsId]
AND [xrxPatIns].[InsType]=1
AND INS2.[InsType]=2
AND INS3.[InsType]=3;
问题是这只能让患者获得3种保险。如果患者只有1个保险,我想返回表INS2和/或INS3的所有患者和空值。 知道怎么做吗?
答案 0 :(得分:2)
虽然这可以在where子句中完成,但最好更改为使用显式连接,因为这样可以使代码更易于阅读。
SELECT
*
FROM [XEREX_TEST].[dbo].[xrxPat]
INNER JOIN [XEREX_TEST].[dbo].[xrxIns]
ON [xrxPat].[PatId] = [xrxIns].[PatId]
INNER JOIN [XEREX_TEST].[dbo].[xrxPatIns]
ON [xrxIns].[RecNo] = [xrxPatIns].[InsId]
AND [xrxPatIns].[InsType] = 1
LEFT JOIN [XEREX_TEST].[dbo].[xrxPatIns] AS INS2
ON [xrxIns].[RecNo] = INS2.[PatId]
AND INS2.[InsType] = 2
LEFT JOIN [XEREX_TEST].[dbo].[xrxPatIns] AS INS3
ON [xrxIns].[RecNo] = INS3.[PatId]
AND INS3.[InsType] = 3;
答案 1 :(得分:0)
使用JOIN表示法而不是逗号。然后让他们LEFT JOIN。
SELECT *
FROM
(SELECT * FROM [XEREX_TEST].[dbo].[xrxPatIns] WHERE [InsType]=1) AS INS1
LEFT JOIN
(SELECT * FROM [XEREX_TEST].[dbo].[xrxPatIns] WHERE [InsType]=2) AS INS2
ON INS1.[PatId] = INS2.[PatId]
LEFT JOIN
(SELECT * FROM [XEREX_TEST].[dbo].[xrxPatIns] WHERE [InsType]=3) AS INS3
ON INS1.[PatId] = INS3.[PatId]
JOIN
[XEREX_TEST].[dbo].[xrxPat]
ON [xrxPat].[PatId]=INS1.[PatId]
JOIN
[XEREX_TEST].[dbo].[xrxIns]
ON [xrxIns].[RecNo]=INS1.[InsId]
;