MySQL - 将ID匹配到最大计数("需要"更优雅的解决方案)

时间:2015-06-16 14:23:36

标签: mysql sql

是否有更好的方法来执行以下操作:

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子句访问第一个。

2 个答案:

答案 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