如何执行查询以获得 mysql 中的最大总和?

how to perform query to get max sum in mysql?

我有这个table:

cart_item_id (primary key)
user_id (int)
shop_item_id (int)
quantity (int)
is_checked_out (tinyint)

从这个 table 我想获得最畅销的商品,即具有最大签出数量的商品,我开发了这个查询,但它返回错误:

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

您的查询有几个问题。一个是您在子查询中使用 group by,其中 return 不止一行。另一个是你有一个子查询作为 max()` 的参数。您可以通过以下方式解决此问题:

SELECT `shop_item_id`
FROM `cart` 
WHERE `is_checked_out` = 1 
group by `shop_item_id` 
having sum(`quantity`) = (select max(q)
                          from (select sum(`quantity`) as q
                                from `cart` 
                                where `is_checked_out` = 1 
                                group by `shop_item_id`
                               ) c
                         ) c;

此版本的查询将 return 多行,如果合适的话,因为最高数量的关系。

以下代码适合您:

SELECT `shop_item_id`
    FROM `cart` 
    WHERE `is_checked_out` = 1  and 
           sum(`quantity`)>=max ( select sum(`quantity`) 
                                  from `cart`
                                  where `is_checked_out` = 1 
                                ) 
 limit 1 ;