MSAccess: Selecting one row out of a one-to-many relationship
-
27-10-2019 - |
문제
In MS Access 2010, I have TableA related one-to-many to TableB, and TableB related one-to-many to TableC. TableC has one numeric field and one date field (in addition to the lookup field).
FormA's datasource is a select query that joins TableA and TableB. I want to add one additional read-only field to FormA that contains the numeric field from TableC from the row with the most recent date.
What's the best way to go about doing this? Should I create a field in TableB and create an update query (or macro?) that populates that column prior to the join query running?
Thanks.
해결책
This is a form and you require read only, so DlookUp should suit : http://support.microsoft.com/kb/208786
= DLookup("[numeric field]", "TableC", "[LookupKey] = " & [PK] & " AND TheDate = DMax(""TheDate"", ""TableC"", ""LookupKey=" & [PK] & """)")
There are two problems with the edit by the OP, the first is that it suggests that date
is an acceptable field name, it is a reserved word and should not be used. Secondly, it suggests that square brackets are needed in DlookUp, they are not.
Alternatively:
Dim rs As DAO.Recordset
s = "SELECT TOP 1 c.[numeric field] " _
& "FROM TableC c " _
& "WHERE c.LookupKey= " & Me.[PK]
& "ORDER BY c.TheDate DESC"
set rs = currentDB.Openrecordset(s)
Me.SomeControl = rs![numeric field]