MySQL SELECT查询返回错误的结果

时间:2017-06-24 09:53:01

标签: mysql sql

我有一张桌子orders(c_id(INT),o_date(DATE),o_price(INT))。我必须找出当前年度每个ID的总价格idMAX值。表格如下:

c_id    o_date     o_price
   1    2017-08-27      30    
   2    2017-05-25     100    
   2    2017-05-02      20    
   1    2017-02-23      80    
   3    2017-01-26      60   
   4    2016-04-22      10    
   2    2016-03-15       5   
   1    2015-09-01       1

我编码如下:

SELECT c_id, MAX(m_price)  
FROM (  SELECT c_id, SUM(o_price) AS
 m_price FROM orders WHERE  
(       YEAR(o_date) = YEAR(curdate())  ) 
GROUP
> BY c_id )AS T

MAX值返回右边但id不适合该MAX值。有没有人建议我的情况?提前谢谢!!

4 个答案:

答案 0 :(得分:1)

如果确保只有一个c_id具有最大的总和,或者您不介意在出现平局时只返回一个结果,那么您可以LIMIT 1以及ORDER BY以获得最大结果。

SELECT
    c_id,
    SUM(o_price) AS m_price
FROM orders
WHERE
    YEAR(o_date) = YEAR(CURDATE())
GROUP BY c_id
ORDER BY m_price DESC
LIMIT 1

如果最大金额可能存在平局,那么有一些稍微有点变通的解决方法,例如

SELECT
    c_id,
    SUM(o_price) AS m_price
FROM orders
WHERE
    YEAR(o_date) = YEAR(CURDATE()) AND
GROUP BY c_id
HAVING SUM(o_price) =
(
    SELECT MAX(t.m_price)
    FROM
    (SELECT SUM(o_price) AS m_price FROM orders
     WHERE YEAR(o_date) = YEAR(CURDATE()) GROUP BY c_id) t
)

上面的查询有点冗长,在其他数据库中我们会使用分析函数来处理这个问题。但由于MySQL不支持这些开箱即用,我们需要采用另一种方式。

答案 1 :(得分:1)

如果您有多个价格,以下内容比Tim的代码稍微简单一些:

SELECT o.c_id, SUM(o.o_price) AS m_price
FROM orders o
WHERE YEAR(o.o_date) = YEAR(CURDATE())
GROUP BY o.c_id
HAVING m_price = (SELECT SUM(o2.o_price)
                  FROM orders o2
                  WHERE YEAR(o2.o_date) = YEAR(CURDATE()
                  GROUP BY c_id
                  ORDER BY SUM(o2.o_price) DESC
                  LIMIT 1
                 );

实际上,使用变量可能会更快。

SELECT o.*
FROM (SELECT o.*, @maxp := GREATEST(@maxp, m_price)
      FROM (SELECT o.c_id, SUM(o.o_price) AS m_price
            FROM orders o
            WHERE YEAR(o.o_date) = YEAR(CURDATE())
            GROUP BY o.c_id
           ) o CROSS JOIN
           (SELECT @maxp := 0) params
     ) o
WHERE m_price = @maxp;

答案 2 :(得分:0)

将您的查询调整为

 SELECT c_id, MAX(m_price)  
    FROM (  SELECT c_id, SUM(o_price) AS
     m_price FROM orders WHERE  
     YEAR(o_date) = YEAR(curdate())
    ) 
    GROUP BY c_id 

答案 3 :(得分:0)

我的解决方案是: 设置@ p1 =(SELECT MAX(m_price)FROM     (         SELECT c_id,SUM(o_price)AS m_price FROM命令WHERE     (         年(o_date)=年(curdate())     )GROUP BY c_id )作为T. );

SELECT c_id from(     从订单WHERE中选择c_id,sum(o_price)为m_price(         年(o_date)=年(curdate())     )c_id分组 )作为WHERE m_price = @ p1