我有4个不同的表,带有字段ID。我想创建一个包含四个字段的第五个表;每个字段分别列出每个表中的所有id。 id与彼此无关,所以我想不出加入它们的内容。如果我联盟,我将不知道哪个表记录来自。我有什么方法可以做到这一点吗?
答案 0 :(得分:1)
这是使用DAO方法的VBA解决方案。为简洁起见,我只包括table1和table3。未经测试,但它应该工作。 :)
Public Sub FillResult()
Dim DB As DAO.Database
Dim rsT As DAO.Recordset ' Target
Dim rs1 As DAO.Recordset, rs3 As DAO.Recordset ' Source tables
Set DB = CurrentDb
' Clean out result table
DB.Execute "DELETE * FROM tResult"
Set rsT = DB.OpenRecordset("tResult", dbOpenDynaset, dbAppendOnly)
Set rs1 = DB.OpenRecordset("SELECT Id FROM table1", dbOpenSnapshot)
Set rs3 = DB.OpenRecordset("SELECT aId FROM table3", dbOpenSnapshot)
' Main loop runs as long as there are records left in at least one source table
Do While Not (rs1.EOF And rs3.EOF)
' Add new record in tResult
rsT.AddNew
' For each source table: if not EOF, copy current value to target table and move to next record
If Not rs1.EOF Then
rsT!table1 = rs1!ID
rs1.MoveNext
End If
If Not rs3.EOF Then
rsT!table3 = rs3!aID
rs3.MoveNext
End If
rsT.Update
Loop
rsT.Close
End Sub
答案 1 :(得分:1)
您可以使用完全外连接(对于使用UNION的MS Access差异逻辑)组合所有这些表,并在进一步查询时排除/处理NULL值。
代表MS Access
SELECT t1.[id] table1,NULL table2,NULL table3,NULL table4 FROM table1 t1 UNION
SELECT NULL table1,t2.[id] table2,NULL table3,NULL table4 FROM table2 t2 UNION
SELECT NULL table1,NULL table2,t3.[aid] table3,NULL table4 FROM table3 t3 UNION
SELECT NULL table1,NULL table2,NULL table3,t4.[bid] table4 FROM table4 t4
结果:
table1 table2 table3 table4
11 NULL NULL NULL
32 NULL NULL NULL
NULL 22 NULL NULL
NULL 45 NULL NULL
NULL NULL 1 NULL
NULL NULL 5 NULL
NULL NULL NULL 2
NULL NULL NULL 7
我知道这不是确切的解决方案,但可能会有所帮助。
对于SQL Server,您可以这样做
SELECT t1.[id] table1
,t2.[id] table2
,t3.[aid] table3
,t4.[bid] table4
FROM table1 t1
FULL OUTER JOIN table2 t2 ON t1.id = t2.id
FULL OUTER JOIN table3 t3 ON t1.id = t3.aid
FULL OUTER JOIN table4 t4 ON t1.id = t4.bid
但是这也会产生NULL值,需要在进一步的查询中排除/处理这个NULL值。