16

我正在根据 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 毫秒。

4

2 回答 2

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)
于 2011-02-25T01:34:23.647 回答
1

Your Col2 never be > then MAX(col2) so i suggest to use col2 = MAX(col2)

so HERE is the QUERY

SELECT * FROM  mytable GROUP BY col1 HAVING  col2 = MAX(  col2 ) 
于 2014-03-11T14:24:31.263 回答