【问题标题】:Access 2003 Nested Selects itcheAccess 2003 嵌套选择痒
【发布时间】:2011-01-24 16:10:30
【问题描述】:

我的查询看起来像:

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]

你们会怎么解决呢?

提前致谢

米卢德 B.

【问题讨论】:

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


    【解决方案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"
    

    【讨论】:

      【解决方案2】:

      您也可以只对TableOfAttribute 表执行一个JOIN,然后执行一个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]
      

      【讨论】:

      • 谢谢!约翰的方法有效,但我想我需要你的方法来轻松地使用外连接来包含空值!谢谢你,兄弟。顺便说一句,Access 有 IIF 但没有 CASE WHEN 语句;)
      • 哦,对了,忘了iif。好吧,至少你明白了;)
      猜你喜欢
      • 2011-05-16
      • 2020-12-07
      • 2019-12-04
      • 1970-01-01
      • 2016-05-22
      • 2011-10-23
      • 2010-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多