访问SQL双喜欢加入

时间:2014-07-08 20:12:44

标签: sql ms-access-2007

SELECT [Table1].[Field1], [Table 1].[Field2], Count([Table2].[ID]) AS [CountOfID]
FROM [Table2] INNER JOIN [Table1] ON ([Table2].[Field1] Like "*" & 
[Table1].[Field1] & "*") AND ([Table2].[Field2] Like "*" & 
[Table1].[Field2] & "*")
GROUP BY [Table1].[Field1], [Table1].[Field2];

以上就是我想要做的。我有两个表,需要使用两个连接(我相信)来创建我需要的两个分组。这些字段通常包含一个列表,如“红/绿/蓝”或“草莓/香蕉/葡萄”和[表2]。[FieldX]将始终包含[​​Table1]的唯一列表。[FieldX]。

结果应如下所示。

[Field1]   [Field2]    [Count]
Strawberry Red         10
Strawberry Green       2
Banana     Yellow      15
Grape      Green       7
Grape      Red         20

问题是我认为加入的计数永远是正确的,如何纠正这一点的帮助非常感谢!

1 个答案:

答案 0 :(得分:1)

使用带通配符的连接没有任何好处,无论如何都会强制对两个表进行串行读取。我不知道这是否有效,但我会尝试按如下方式编写此查询:

SELECT [Table1].[Field1], [Table 1].[Field2], Count([Table2].[ID]) AS [CountOfID]
FROM [Table2], [Table1] 
WHERE ([Table2].[Field1] Like "*" & [Table1].[Field1] & "*") 
  AND ([Table2].[Field2] Like "*" & [Table1].[Field2] & "*")
GROUP BY [Table1].[Field1], [Table1].[Field2];