我认为解决这个问题的最简单方法是使用 VBA 创建查询定义。
我将假设有一个名为key
两个表共有的列。
我在这里发现您可以使用集合来制作类似字典的结构。我将使用它来构建字段列表。
所以,我们开始:
public function contains(col as Collection, key as variant) as boolean
dim obj as variant
on error goto err
contains = True
obj = col(key)
exit function
err:
contains = false
end function
public sub create_this_query(tbl1 as String, tbl2 as String, keyField as String)
' tbl1 and tbl2 are the names of the tables you'll use
dim db as DAO.database, rs1 as DAO.recordset, rs2 as DAO.recordset
dim columns as Collection
dim strSQL as String
dim i as integer
dim obj as variant, colName as String
set db = currentdb()
set tbl1 = db.openrecordset(tbl1, dbopendynaset, dbreadonly)
set tbl2 = db.openrecordset(tbl2, dbopendynaset, dbreadonly)
set columns = new Collection
' Let's create the field list (ommiting the keyField)
for i = 1 to tbl1.fields.count
if not contains(columns, tbl1.fields(i).Name) _
and tbl1.fields(i).Name <> keyField then
columns.add tbl1.fields(i).Name, tbl1.fields(i).Name
end if
next i
for i = 1 to tbl2.fields.count
if not contains(columns, tbl2.fields(i).Name) _
and tbl2.fields(i).Name <> keyField then
columns.add tbl1.fields(i).Name, 1 ' The value is just a placeholder
end if
next i
' Now let's build the SQL instruction
strSQL = "select [a].[" & keyField & "]"
for colName in columns
strSQL = strSQL & ", [" & colName & "]"
next obj
strSQL = strSQL & " " & _
"from " & _
" (" & _
" select [" & keyField & "] from [" & tbl1 & "] " & _
" union " & _
" select [" & keyField & "] from [" & tbl2 & "] " & _
" ) as a " & _
"left join [" & tbl1 & "] as t1 " & _
" on a.[" & keyField & "] = t1.[" & keyField & "] " & _
"left join [" & tbl2 & "] as t2 " & _
" on a.[" & keyField & "] = t2.[" & keyField & "] "
' Finally, let's create the query object
db.createQueryDef("myNewQuery", strSQL)
end sub
希望这可以帮助