子查询执行问题

时间:2015-07-17 17:00:36

标签: sql

以下代码正确,因为它显示了我

SELECT TOP 3 P.CategoryID,SUM(OD.Quantity) From "Order Details" AS OD
            INNER JOIN
            Products AS P
            ON OD.ProductID=P.ProductID
            GROUP BY P.CategoryID
            ORDER BY SUM(OD.Quantity) DESC

结果是

CategoryID   sum
1            9532
4            9149
3            7906

但是当我尝试子查询时遇到了这个错误。

以下代码是导致错误的当前问题。错误是 "当子查询未与EXISTS一起引入时,只能在选择列表中指定一个表达式。"

SELECT CategoryName FROM Categories WHERE CategoryID =
    (
    SELECT TOP 3 P.CategoryID,SUM(OD.Quantity) From "Order Details" AS OD
    INNER JOIN
    Products AS P
    ON OD.ProductID=P.ProductID
    GROUP BY P.CategoryID
    ORDER BY SUM(OD.Quantity) DESC
    )

我不确定如何解决它或以任何方式更改代码,我确实尝试不将categoryID归类为失败,因为它甚至没有显示任何结果。

期望的结果应该是

CategoryName     
Beverages
Dairy Products
Confections

4 个答案:

答案 0 :(得分:1)

MySQL使用LIMIT,而不是TOP。这个问题用MySQL标记,而不是SQL Server,所以我正在回答。

SELECT
  P.CategoryID, SUM( OD.Quantity )
FROM
  OrderDetails AS OD
  INNER JOIN Products AS P
    ON OD.ProductID=P.ProductID
GROUP BY
  P.CategoryID
ORDER BY
  SUM( OD.Quantity ) DESC
LIMIT 3;

根据@Kjell建议的精神,MySQL不允许以这种方式使用IN Predicate。改为使用INNER JOIN:

SELECT
  CategoryName
FROM
  Categories
  INNER JOIN 
  (
    SELECT
      P.CategoryID, SUM( OD.Quantity )
    FROM
      OrderDetails AS OD
      INNER JOIN Products AS P
        ON OD.ProductID=P.ProductID
    GROUP BY
      P.CategoryID
    ORDER BY
      SUM( OD.Quantity ) DESC
    LIMIT 3
  ) AS Quants
  ON Quants.CategoryID = Categories.CategoryID;

如果您使用的是SQL Server,请更新您的问题并使用IN谓词或使用INNER JOIN示例与TOP而不是LIMIT:

SELECT
  CategoryName
FROM
  Categories
WHERE
  CategoryID IN
  (
    SELECT TOP 3
      P.CategoryID
    FROM
      OrderDetails AS OD
      INNER JOIN Products AS P
        ON OD.ProductID=P.ProductID
    GROUP BY
      P.CategoryID
    ORDER BY
      SUM( OD.Quantity )
  )

- 或者

SELECT
  CategoryName
FROM
  Categories
  INNER JOIN 
  (
    SELECT TOP 3
      P.CategoryID, SUM( OD.Quantity ) AS q
    FROM
      OrderDetails AS OD
      INNER JOIN Products AS P
        ON OD.ProductID=P.ProductID
    GROUP BY
      P.CategoryID
    ORDER BY
      SUM( OD.Quantity )
  ) AS Quants
  ON Quants.CategoryID = Categories.CategoryID

答案 1 :(得分:0)

尝试将“CategoryID =”更改为“CategoryID IN”

答案 2 :(得分:0)

问题在于where CategoryID = ( SELECT Top 3......

您正在使用=进行比较,这意味着子查询应该只返回一个categoryid 但是在这里你无论如何选择前三名,因此错误即将来临。

在where子句中使用IN而不是=来解决该错误。

答案 3 :(得分:0)

您不应在内部查询中选择SUM(OD.Quantity)。

    SELECT CategoryName FROM Categories WHERE CategoryID IN
            (
            SELECT TOP 3 P.CategoryID From "Order Details" AS OD
            INNER JOIN
            Products AS P
            ON OD.ProductID=P.ProductID
            GROUP BY P.CategoryID
            ORDER BY SUM(OD.Quantity) DESC
            )