MySQL GROUP BY和HAVING

时间:2011-02-25 01:23:54

标签: mysql group-by having

我正在根据列X对结果进行分组,我希望返回组中列Y值最高的行。

SELECT * 
FROM   mytable 
GROUP  BY col1 
HAVING col2 >= (SELECT MAX(col2) 
                FROM   mytable AS mytable2 
                WHERE  mytable2.col1 = mytable.col1 GROUP BY mytable2.col1) 

我想优化上面的查询。没有子查询是否可行?

我找到了解决方案,它比你想象的更简单:

SELECT * FROM (SELECT * FROM mytable ORDER BY col2 DESC) temp GROUP BY col1

在20,000行上运行5毫秒。

2 个答案:

答案 0 :(得分:13)

使用JOIN的派生表/内联视图:

SELECT x.* 
  FROM mytable x
  JOIN (SELECT t.col1,
               MAX(t.col2) AS max_col2
          FROM MYTABLE t
      GROUP BY t.col1) y ON y.col1 = x.col1
                        AND y.max_col2 >= x.col2

请注意,如果有多个相关的x记录,则会重复y个记录。要删除重复项,请使用DISTINCT

SELECT DISTINCT x.* 
  FROM mytable x
  JOIN (SELECT t.col1,
               MAX(t.col2) AS max_col2
          FROM MYTABLE t
      GROUP BY t.col1) y ON y.col1 = x.col1
                        AND y.max_col2 >= x.col2

以下是未经测试的,但不会返回重复项(假设有效):

SELECT x.* 
  FROM mytable x
 WHERE EXISTS (SELECT NULL
                 FROM MYTABLE y
                WHERE y.col1 = x.col1
             GROUP BY y.col1
               HAVING MAX(y.col2) >= x.col2)

答案 1 :(得分:1)

你的Col2永远不会>那么MAX(col2)所以我建议使用col2 = MAX(col2)

所以HERE是QUERY

SELECT * FROM  mytable GROUP BY col1 HAVING  col2 = MAX(  col2 )