3

我在 Access 2003 中有三个查询,我需要将它们合并到一个查询中。并非所有记录都存在于所有三个表上,所以我想我想要一个完整的外部连接。

查询 1 字段: Record number, surname, firstname, subcentre

查询 2 个字段: Record number, surname, firstname, case worker

查询 3 个字段: Record number, surname, firstname, doctor

我需要能够显示:

Record number, surname, firstname, case worker, doctor, subcentre

但是,目前我可以锻炼如何使用左连接,然后在两个查询之间使用右连接联合,但不知道如何将其扩展到三个查询。

有什么想法/建议吗?

4

1 回答 1

3

How about:

SELECT a.[Record number], a.surname, a.firstname, 
       t1.subcentre, t2.[case worker], t3.doctor
FROM
(((SELECT [Record number], surname, firstname FROM T1
UNION
SELECT [Record number], surname, firstname FROM T2
UNION
SELECT [Record number], surname, firstname FROM T3) As A
LEFT JOIN T1 ON A.[Record number]=T1.[Record number])
LEFT JOIN T2 ON A.[Record number]=T2.[Record number])
LEFT JOIN T3 ON A.[Record number]=T3.[Record number]

The use of UNION rather than UNION ALL in the query creates a unique list of [Record number], surname, first name taken from all three tables. The derived table can then be used to LEFT JOIN to the other three tables. LEFT JOIN ensures that all records from the derived tables are included.

As usual with SQL, there are other, similar ways to do this. The above would be slow on a very large file, but unless you have something other than a Jet/ACE back-end, it is unlikely that you will notice any delay.

With, say, an SQL Server back-end, you would use a pass-through query and t-sql syntax. With MySQL back-end, I think you are obliged to use a passthrough query when you go above the one UNION statement.

于 2012-06-24T08:21:18.767 回答