是否有更好的方法来执行以下操作:
SELECT ProductID, MAX(a.countProductID)
FROM
(
SELECT ProductID, COUNT(ProductID) as countProductID
FROM SalesOrderDetail
LEFT JOIN Product USING (ProductID)
GROUP BY ProductID
) as a
WHERE a.countProductID = (SELECT MAX(x.countProductID) FROM
(
SELECT ProductID, COUNT(ProductID) as countProductID
FROM SalesOrderDetail
LEFT JOIN Product USING (ProductID)
GROUP BY ProductID
) as x
);
因为我使用相同的子查询两次。但是,我无法从WHERE子句访问第一个。
答案 0 :(得分:1)
我想任务是查找具有最大销售量的产品或产品。首先,您不应该加入PRODUCT
表,因为您需要的所有信息都在SalesOrderDetail
表中。然后使用LIMIT 1
查找最大数量,HAVING
选择所有具有最大数量的产品:
SELECT ProductID, COUNT(ProductID) as countProductID
FROM SalesOrderDetail
GROUP BY ProductID
HAVING COUNT(ProductID) = (SELECT COUNT(ProductID) as countProductID
FROM SalesOrderDetail
GROUP BY ProductID
ORDER BY countProductID DESC
LIMIT 1 )
答案 1 :(得分:0)
最终答案
SELECT ProductID, COUNT(ProductID) as countProductID
FROM SalesOrderDetail
LEFT JOIN Product USING (ProductID)
GROUP BY ProductID
ORDER BY countProductID desc
LIMIT 1