简体   繁体   中英

Getting the latest entries for grouped by the foreign key in MySQL

I got the table with the fields: id, foreign_key, created, modified

It's a table that logs the changes of a part of my program. What I want is to retrieve the latest logs grouped by the foreign key. How do I do this?

EDIT: to summarize, how do I order first before I group?

SELECT ... GROUP BY ... HAVING MAX(modified)

Uncorrelated subquery:

SELECT t.*
       , a.*
  FROM mytable t
       INNER JOIN 
           (select b.foreign_key
                   , max(b.modified) as max_modified 
              from mytable b 
           group by 1) a
       ON a.foreign_key = t.foreign_key 
      AND a.max_modified = t.modified

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