选择select语句的select查询

时间:2010-01-11 18:15:57

标签: sql ms-access select ms-access-2007

我甚至不知道我是否以正确的方式进行此查询。 有一个Sandwiches表有7个字段,其中2个是组合框(TypeBread)。

所以我做了一个查询,将所有组合框值组合成一个查询,如下所示:

SELECT TypesAndBreads.TBName, TypesAndBreads.Type
FROM (SELECT [Sandwiches Types].[Sandwich Type] As TBName, "Sandwich Type" As Type
    FROM [Sandwiches Types]
UNION ALL
    SELECT Breads.Bread As TBName, "Bread" As Type 
    FROM Breads)  AS TypesAndBreads;

我现在得到表格的平面值我想要计算每个TypesAndBreads.TBName下的所有三明治。我有这个,只是为了确保它适用于所有三明治:

SELECT TypesAndBread.Type, TypesAndBread.TBName,
       (SELECT Count(Sandwiches.[SandwichID]) As SandwichCount
        FROM Sandwiches) As SandwichCount
FROM TypesAndBread;

但我想在子查询中引用当前的Type和TBName。像这样:

SELECT TypesAndBread.Type, TypesAndBread.TBName,
       (SELECT Count(Sandwiches.[SandwichID]) As SandwichCount
        FROM Sandwiches
        WHERE Sandwiches.[TypesAndBread.Type] = Sandwiches.[TypesAndBread.TBName]) As SandwichCount
FROM TypesAndBread;

但当然这不起作用。我不认为会这样,只是想试一试。我想在打开报告时可能会用VBA构建查询,这个查询将基于这个查询。

所以我想我的问题是:有没有办法在子查询中引用当前选定的字段?或者有不同的方法来解决这个问题吗?

感谢您的帮助

修改 我的表结构是这样的:

Sandwiches的字段

| SandwichID | Name | Date Added | Chef | Sandwich Type | Bread | Reviewed By |

其中Sandwich TypeBread是这些表的查找字段:

Sandwiches Types的字段

| Sandwich Type |

Breads的字段

| Bread |

TypesAndBreads查询结合了三明治类型和面包表,但原因是我可以获得所有具有该类型或面包的三明治的数量。像这样的结果:

+=============================================+
|      Type     |    TBName   | SandwichCount |
+=============================================+
| Sandwich Type | Turkey Club |            10 |
| Bread         | Italian     |             5 |
| Bread         | Garlic      |             8 |
+---------------------------------------------+

示例结果的第一行基本上说有三个三明治记录,三明治类型字段等于土耳其俱乐部。

我希望能更好地解释它。

2 个答案:

答案 0 :(得分:22)

不确定Access是否支持它,但在大多数引擎(包括SQL Server)中,这称为相关子查询并且工作正常:

SELECT  TypesAndBread.Type, TypesAndBread.TBName,
        (
        SELECT  Count(Sandwiches.[SandwichID]) As SandwichCount
        FROM    Sandwiches
        WHERE   (Type = 'Sandwich Type' AND Sandwiches.Type = TypesAndBread.TBName)
                OR (Type = 'Bread' AND Sandwiches.Bread = TypesAndBread.TBName)
        ) As SandwichCount
FROM    TypesAndBread

通过索引TypeBread并在UNION上分发子查询,可以提高效率:

SELECT  [Sandwiches Types].[Sandwich Type] As TBName, "Sandwich Type" As Type,
        (
        SELECT  COUNT(*) As SandwichCount
        FROM    Sandwiches
        WHERE   Sandwiches.Type = [Sandwiches Types].[Sandwich Type]
        )
FROM    [Sandwiches Types]
UNION ALL
SELECT  [Breads].[Bread] As TBName, "Bread" As Type,
        (
        SELECT  COUNT(*) As SandwichCount
        FROM    Sandwiches
        WHERE   Sandwiches.Bread = [Breads].[Bread]
        )
FROM    [Breads]

答案 1 :(得分:5)

我过度复杂了。经过长时间休息并返回后,可通过以下简单查询完成所需的输出:

SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;

感谢您的回答,这有助于我的思考。