我有这张表:
cart_item_id (primary key)
user_id (int)
shop_item_id (int)
quantity (int)
is_checked_out (tinyint)
我想从这个表中获取最畅销的商品,即 checkout 数量最多的商品,我开发了这个查询,但它返回了错误:
SELECT `shop_item_id`
FROM `cart`
WHERE `is_checked_out` = 1
group by `shop_item_id`
having sum(`quantity`) > max(
select sum(`quantity`)
from `cart`
where `is_checked_out` = 1
group by `shop_item_id` )
错误是:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select sum(`quantity`) from `cart` where `is_checked_out` = 1 group by `shop_ite' at line 1
那么我的查询有什么问题呢?
最佳答案
按数量排序,只取第一条记录
SELECT `shop_item_id`, sum(`quantity`)
FROM `cart`
WHERE `is_checked_out` = 1
group by `shop_item_id`
order by sum(`quantity`) desc
limit 1
关于mysql - 如何在mysql中执行查询以获得最大总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28045878/