Access 2003 Nested选择itche

时间:2011-01-24 16:10:31

标签: sql ms-access select query-optimization ms-access-2003

我的查询看起来像:

SELECT *,
       (SELECT Attribute FROM TableOfAttributes WHERE KeyField = MyTable.KeyField AND Type = "A") AS Attribute1,
       (SELECT Attribute FROM TableOfAttributes WHERE KeyField = MyTable.KeyField AND Type = "B") AS Attribute2,
       (SELECT Attribute FROM TableOfAttributes WHERE KeyField = MyTable.KeyField AND Type = "C") AS Attribute3
FROM
       MyTable

确实!在MyTable中,信息是水平的,但在TableOfAttributes中它是垂直的,我正在试图弄清楚如何破坏这些嵌套查询,因为目前执行时间太长(超过一个小时)。

总结一下:我有一个带有条目的表,每个条目在另一个表中都有属性,每个属性都存储在一个记录中,一个条目有3个属性。

我想出现:

[Entry ID] [Entry Something] [Attribute1] [Attribute2] [Attribute3]

你们怎么解决这个问题?

提前致谢

Miloud B。

2 个答案:

答案 0 :(得分:1)

您可以使用每个表的别名加入表。如果有一个Att表中没有匹配的实例,则需要外连接。

SELECT m.*, Att1.Attribute, Att2.Attribute, Att3.Attribute 
FROM MyTable m, TableOfAttributes Att1, TableOfAttributes Att2, TableOfAttributes Att3 
WHERE Att1.KeyField = m.KeyField AND Type = "A" 
and Att2.KeyField = m.KeyField AND Type = "B"
and Att3.KeyField = m.KeyField AND Type = "C"

答案 1 :(得分:1)

您还可以使用JOIN表格只执行一次TableOfAttribute,然后执行GROUP BY

SELECT  [Entry ID], [Entry Something], 
        MIN(CASE WHEN [Type] = 'A' THEN Attribute ELSE NULL END) AS Attribute1,
        MIN(CASE WHEN [Type] = 'B' THEN Attribute ELSE NULL END) AS Attribute2,
        MIN(CASE WHEN [Type] = 'C' THEN Attribute ELSE NULL END) AS Attribute3
FROM MyTable 
LEFT JOIN TableOfAttributes
ON MyTable.KeyField = TableOfAttributes.KeyField
GROUP BY [Entry ID], [Entry Something]