MySQL - 如何获取按特定字段分组的最新行值?

时间:2013-03-14 09:14:06

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

让我们说这个表名为表A

id         foreign_id   value
1             1         x
2             2         y
3             1         y
4             2         x
5             3         x

其中id是主键

你如何得到最新的行(我们将按照id的顺序)以外国ID分组?基本上,我想要的是

id     foreign_id     value
3      1              y
4      2              x
5      3              x  

4 个答案:

答案 0 :(得分:3)

尝试此查询,

SELECT t.id, t.foreign_id, t.value FROM #temp t
WHERE t.id IN (SELECT max(id) FROM #temp GROUP BY foreign_id)

#temp替换为您的实际表名。

答案 1 :(得分:2)

尝试此查询

SELECT max(id) AS ID, foreign_id FROM tbl
GROUP BY  foreign_id

如果还需要值,那么

SELECT a.ID, a.foreign_id, a.value  
FROM tbl a,
(SELECT max(id) AS ID, foreign_id 
        FROM tbl GROUP BY foreign_id) b
WHERE a.id = b.id AND 
      a.foreign_id = b.foreign_id

<强> FIDDLE

答案 2 :(得分:0)

SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT  foreign_ID, max(id) max_ID
            FROM    tableName
            GROUP   BY foreign_ID
        ) b ON  a.foreign_ID = b.foreign_ID AND
                a.ID = b.max_ID

输出

╔════╦════════════╦═══════╗
║ ID ║ FOREIGN_ID ║ VALUE ║
╠════╬════════════╬═══════╣
║  3 ║          1 ║ y     ║
║  4 ║          2 ║ x     ║
║  5 ║          3 ║ x     ║
╚════╩════════════╩═══════╝

答案 3 :(得分:0)

`SELECT MAX(id) AS ID, 
       foreign_id,
       value 
 FROM tbl
 GROUP BY  foreign_id ASC`

这个ans对于少量结果非常好,但是如果你使用大量数据,那么它可能只对“值”字段有错误的值。另一种方法更适合您获得正确的值,这是代码。

`SELECT MAX(id) AS ID, 
       foreign_id,
       value 
 FROM tbl
 WHERE id in ( SELECT MAX(id) FROM tbl )
 GROUP BY  foreign_id ASC`