我有一个类似于此的内部关系表:
BOM CMP CMPTYPE
1 JTS A
1 RED PT
1 BLUE PT
2 QQ PT
2 ZZ PT
JTS 33 PT
JTS 55 PT
JTS WID A
WID LOG PT
WID 191 DWG
WID BOX PACK
. . .
在我的查询中,我需要选择BOM =“1”的所有记录以及BOM =“1”的子配置存在的所有记录,在表格中表示为CMPTYPE =“A”。
以下是我所遵循的配置的准确表示:
1 RED PT
1 BLUE PT
1 JTS A
JTS 33 PT
JTS 55 PT
JTS WID A
WID LOG PT
WID 191 DWG
WID BOX PACK
这可以在单个Access Inner连接中完成吗?
答案 0 :(得分:0)
如果你可以使用VBA,你绝对可以做到。
以下是使用上述数据结构的示例
首先创建一个查询(用“TableName”替换“Table1”)
另存为qdfInitQuery
PARAMETERS [Init BOM] Text ( 255 ), [Init CMPType] Text ( 255 );
SELECT CMP
FROM Table1
WHERE (BOM=[Init BOM]) AND (CMPTYPE=[Init CMPType]);
在新模块中输入此鳕鱼 e
Option Compare Database
Option Explicit
Public Sub testConfig()
ConfigSelect BOMValue:="1", CMPTypeValue:="A"
End Sub
Public Sub ConfigSelect(BOMValue As String, CMPTypeValue As String)
Const MY_TABLE As String = "Table1" ' replace with your Table name here
Const REPLACE_LIST As String = "<ListOfBOMs>"
Const SELECT_CMPS As String = "SELECT CMP FROM [" & MY_TABLE & "] WHERE [BOM] In (" & REPLACE_LIST & ")"
Const VALID_RECORDS As String = "SELECT * FROM [" & MY_TABLE & "] WHERE [BOM] In (" & REPLACE_LIST & ")"
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim qdf As DAO.QueryDef
Dim strList As String
Dim strBigList As String
Dim strSQL As String
Set db = CurrentDb
' Add First Value
strList = ","
' Get Initial List
Set qdf = db.QueryDefs("qdfInitQuery")
With qdf
.Parameters("Init BOM") = "1"
.Parameters("Init CMPType") = "A"
Set rs = .OpenRecordset(dbOpenSnapshot, dbReadOnly)
End With
With rs
While Not .EOF
strList = strList & """" & !CMP & """," 'leave trailing comma for searches
.MoveNext
Wend
.Close
End With
qdf.Close
If strList = "," Then
Exit Sub
End If
' Create Big List
strBigList = strList
' Infinite Loop until No More Matches Found
Do Until strList = ","
strSQL = Replace(SELECT_CMPS, REPLACE_LIST, Mid$(strList, 2))
Set rs = db.OpenRecordset(strSQL, dbOpenSnapshot, dbReadOnly)
If rs.EOF Then
rs.Close
Exit Do
End If
strList = ","
With rs
While Not .EOF
' Only Add if it hasn't already been found
If InStr(strBigList, ",""" & !CMP & """,") <= 0 Then
strList = strList & """" & !CMP & """," ' leave trailing comma for searches
Else
Debug.Print "Ignoring Duplicate: " & !CMP
End If
.MoveNext
Wend
.Close
End With
If strList <> "," Then
strBigList = strBigList & Mid$(strList, 2)
End If
Loop
' Add first value to initial list
strBigList = """" & BOMValue & """" & strBigList
strSQL = Replace(VALID_RECORDS, REPLACE_LIST, strBigList)
Set rs = db.OpenRecordset(strSQL, dbOpenSnapshot, dbReadOnly)
With rs
While Not .EOF
' Only Add if it hasn't already been found
Debug.Print !BOM & vbTab & !CMP & vbTab & !CMPType
.MoveNext
Wend
.Close
End With
db.Close
Set rs = Nothing
Set qdf = Nothing
Set db = Nothing
End Sub