0

我的数据库包括几个查找表(在 UI 表单上显示为下拉菜单)。

例如,

customer_data - 客户人口统计信息。

lookup_car - 存储汽车描述(Pinto、Vega、Reliant Robin、Mustang、Corvette)

junction_car_customer - 将客户与一辆或多辆汽车连接起来

客户 Jeremy Clarkson (cust_id: 1) 拥有三辆汽车。他的记录下拉菜单显示:

Pinto (car_id=100)
Reliant Robin (car_id=101)
Vega (car_id=102)

junction_car_customer 数据如下所示:

cust_id    car_id
1          100
1          101
1          102

我试图返回一行显示客户名称和拥有的模型(作为分号分隔的字符串)。

这是我的查询:

SELECT 
 cd.cust_id,
 cd.name_first,
 cd.name_last,
 jcc.car_id,
 lc.car_desc
FROM
 ((customer_data AS cd)
 LEFT JOIN ju_cust_car AS jcc ON jcc.cust_id = cd.cust_id)
 LEFT JOIN lookup_cars AS lc ON lc.car_id = jcc.car_id
ORDER BY 
 cd.name_last

这将返回:

cust_id name_first name_last car_id car_desc
1       Jeremy     Clarkson  100    Pinto
1       Jeremy     Clarkson  101    Reliant Robin
1       Jeremy     Clarkson  102    Vega 

我想要的是:

cust_id name_first name_last car_desc
1       Jeremy     Clarkson  Pinto;Reliant Robin;Vega

有没有返回上述结果的有效方法?

4

1 回答 1

1

正如 HansUp 所说,您需要使用自定义 VBA 函数。如果数据是相当静态的,您可以通过缓存结果来加快速度。所以...

1) 在 VB 编辑器中,添加对“Microsoft Scripting Runtime”的引用(我们将需要Dictionary该库中的类)。

2)创建一个新的标准模块,并添加代码如下:

Option Explicit

Private mCache As New Scripting.Dictionary

Sub ClearCarDescCache(Optional cust_id)
  If IsMissing(cust_id) Then
    mCache.RemoveAll
  Else
    mCache.Remove CInt(cust_id)
  End If
End Sub

Function GetCarDescList(cust_id) As String
  If mCache.Exists(cust_id) Then
    GetCarDescList = mCache(cust_id)
    Exit Function
  End If
  Dim RS As DAO.Recordset, S As String
  Set RS = CurrentDb.OpenRecordset( _
    " SELECT car_desc " + _
    " FROM junction_car_customer INNER JOIN lookup_car " + _
    "   ON junction_car_customer.car_id = lookup_car.car_id " + _
    " WHERE cust_id = " & cust_id & _
    " ORDER BY car_desc", dbOpenForwardOnly)
  While Not RS.EOF
    If Len(S) = 0 Then
      S = RS(0)
    Else 
      S = S + ";" & RS(0)
    End If
    RS.MoveNext
  Wend
  mCache.Add cust_id, S
  GetCarDescList = S
End Function

3) 主查询现在看起来像这样:

SELECT cust_id, name_first, name_last, GetCarDescList(cust_id) AS car_desc
FROM customer_data
ORDER BY name_last

4) 根据需要添加显式调用ClearCarDescCache

于 2013-11-04T15:10:00.677 回答