简体   繁体   中英

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

Lets say we have this table named table 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

How do you get the latest rows(we are going to base this in the order of the id ) grouped by foreign 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.

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

╔════╦════════════╦═══════╗
║ 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. 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`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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