【问题标题】:MySQL select SUM of results with a LIMITMySQL 选择具有 LIMIT 的结果的总和
【发布时间】:2012-04-10 07:05:55
【问题描述】:

我有一张桌子,上面摆满了这些物品的物品和价格。我想获取价格最高的 3 件商品的总和。

我想也许SELECT SUM(items.price) FROM items ORDER BY items.price LIMIT 3 但这似乎没有奏效。这可能吗?谢谢!

【问题讨论】:

    标签: mysql sum


    【解决方案1】:

    我没有测试过这个,我只是把它写在我的记忆中。您可以尝试以下方法:

    SELECT * AS total FROM items ORDER BY price DESC
    SELECT SUM(price) FROM total LIMIT 3;
    

    编辑:我很慢

    【讨论】:

      【解决方案2】:

      使用子查询或类似的东西。只是一个想法,因为我没有测试过实际的查询。

      SELECT SUM(items.price) from (select price FROM items ORDER BY items.price LIMIT 3)
      

      【讨论】:

      • 正确答案,除了当我写SUM(items.price) 时似乎查询失败,但忽略了表格,即。 SUM(price) 查询有效
      【解决方案3】:

      LIMIT 影响查询返回的行数,SUM 只返回一个。基于this thread,您可能想尝试:

      SELECT sum(price) 
      FROM (SELECT price
            FROM items
            ORDER BY price DESC
            LIMIT 3
      ) AS subquery;
      

      【讨论】:

        【解决方案4】:

        只需使用子选择:

        select sum(prices) from (SELECT SUM(items.price) FROM items ORDER BY items.price LIMIT 3) as prices
        

        【讨论】:

          【解决方案5】:
          select sum(price) from (select items.price from items order by items.price desc limit 3) as subt;
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-11-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-06-09
            相关资源
            最近更新 更多