选择列中具有最大值的行

时间:2021-04-30 01:24:52

标签: mysql database select max

我正在尝试选择 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'”

有没有办法在一个查询中完成这项工作?

1 个答案:

答案 0 :(得分:1)

如果您只需要具有最大值的单行,则使用 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;