首页 > 解决方案 > 选择列中具有最大值的行

问题描述

我正在尝试选择 numTimesPurchasedTable 中在 numTimesPurchased 列上具有最大值的行

SELECT item, title, MAX(numTimesPurchased) 
FROM (SELECT Purchase.item, Item.title, SUM(quantity) AS numTimesPurchased 
FROM Item INNER JOIN Purchase ON Item.id = Purchase.item 
GROUP BY item, title) AS numTimesPurchasedTable;

numTimesPurchasedTable 看起来像这样

item title numTimesPurchased
1    a     4
2    b     7
3    c     7

但是,我收到错误:“错误代码:1140。在没有 GROUP BY 的聚合查询中,SELECT 列表的表达式 #1 包含非聚合列 'numTimesPurchasedTable.item'”

有没有办法在一个查询中完成此操作?

标签: mysqldatabaseselectmax

解决方案


如果您只需要具有最大值的单行,则使用 LIMIT:

SELECT Purchase.item, Item.title, SUM(quantity) AS numTimesPurchased 
FROM Item INNER JOIN Purchase ON Item.id = Purchase.item 
GROUP BY item, title
ORDER BY numTimesPurchased DESC LIMIT 1;

推荐阅读