简体   繁体   English

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

[英]MySQL - How to get latest row value grouped by a certain field?

Lets say we have this table named table A 假设我们有一个名为表A的表

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

where id is the primary key 其中id是主键

How do you get the latest rows(we are going to base this in the order of the id ) grouped by foreign id? 您如何获取按外国ID分组的最新行(我们将以id的顺序为基础)? Basically, what I want to get is 基本上,我想得到的是

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

Try this query, 试试这个查询

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

Replace #temp with your actual table name. #temp替换为您的实际表名。

Try this query 试试这个查询

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

If value is also needed then 如果还需要值,那么

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 小提琴

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

OUTPUT OUTPUT

╔════╦════════════╦═══════╗
║ ID ║ FOREIGN_ID ║ VALUE ║
╠════╬════════════╬═══════╣
║  3 ║          1 ║ y     ║
║  4 ║          2 ║ x     ║
║  5 ║          3 ║ x     ║
╚════╩════════════╩═══════╝
`SELECT MAX(id) AS ID, 
       foreign_id,
       value 
 FROM tbl
 GROUP BY  foreign_id ASC`

This ans is quite fine for small amount of result but if you use large amount of data then it might wrong value for only "value" fields. 对于少量结果,此ans很好,但是如果您使用大量数据,则仅“值”字段的值可能会错误。 Another approach is better for you to get proper value and here is this code. 另一种方法是使您获得适当的价值更好,这是此代码。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM