How to select the last two records for each topic_id in MySQL

mysql, sql

Solution

SELECT max(id), max(topic_id) FROM msg
GROUP BY topic_id

UNION

SELECT max(id), max(topic_id) FROM msg
WHERE id not in (
    SELECT max(id) as id FROM msg
    GROUP BY topic_id)
GROUP BY topic_id

Problem

I have to select the last two records for every topic. ex: table: msg ``` id | topic_id ------------ 1 | 1 2 | 1 3 | 1 4 | 1 5 | 2 6 | 2 7 | 2 8 | 3 9 | 3 10 | 3 ``` I want to obtain these rows: ``` 3 1 4 1 6 2 7 2 9 3 10 3 ``` How can I do this?

Original source