选择最大列和行ID

时间:2013-08-23 06:44:30

标签: mysql sql group-by max greatest-n-per-group

有没有办法告诉MySQL这样做的事情

SELECT id, MAX(seq) FROM t1 GROUP BY ident;

我还可以获得id值吗?我知道我不应该使用id如果它不在一个组中,但我觉得做多次传递以获得具有最大seq字段的行ID时它很奇怪。那么最有效的方法是什么? id是主键

4 个答案:

答案 0 :(得分:2)

SELECT  a.*
FROM    tableName
        INNER JOIN
        (
            SELECT  ident, MAX(seq) seq
            FROM    tableName
            GROUP   BY ident
        ) b ON a.ident = b.ident AND
                a.seq = b.seq

答案 1 :(得分:1)

尝试使用自我加入:

SELECT t1.* FROM MyTable t1
  JOIN
      (SELECT ident, MAX(seq) AS MAX_Seq 
         FROM MyTable 
        GROUP BY ident
      ) t2
    ON t1.seq = t2.MAX_Seq
   AND t1.ident = t2.ident

请参阅this sample SQLFiddle

答案 2 :(得分:1)

Mabye:

SELECT MAX(a.seq), (SELECT id FROM t1 as b where b.ident=a.ident AND MAX(a.seq) = b.seq LIMIT 1) as id FROM t1 AS a GROUP BY a.ident;

Fiddle

答案 3 :(得分:0)

究竟是什么?

我想你也可以订购你的结果?

SELECT id FROM t1 GROUP BY ident ORDER BY seq DESC

关于其他答案,seq在另一个表中?