开发者

How to get the last 3 distinct ids from a mysql table

How to get the last 3 distinct ids from a mysql table

Ok so basically I have my database table. The first column is the id. Th开发者_运维技巧e second is a pkg_id. The 3rd is not important and the 4th is the previous id that the pkg_id was located at. I need to pull the last 3 pkg_id's from the table. So basically I need to pull the last 3 17879 pkg_id's and the last 3 3075. So in this example I need to pull id 9 , 7 , 6 for 17879 and id 8, 5, 3 for 3075.

I can't get my head around it. I do have access to the previous id that it was. So you see that for id 9 it says that 17879 was last in id 7. That id 8 was last in id 5.

If anybody could help me write a query that would be great. I'm also using Java for database access so it doesn't have to be just in mysql. Thanks so much.


SELECT  m.*
FROM    (
        SELECT  pkg_id,
                COALESCE(
                (
                SELECT  id
                FROM    mytable mi
                WHERE   mi.pkg_id = md.pkg_id
                ORDER BY
                        id DESC
                LIMIT 2, 1
                ), 0) AS mid
        FROM    (
                SELECT  DISTINCT pkg_id
                FROM    mytable
                ) md
        ) q
JOIN    mytable m
ON      m.pkg_id <= q.pkg_id
        AND m.pkg_id >= q.pkg_id
        AND m.id >= q.mid

Create an index on mytable (pkg_id, id) for this to work fast.

Note this condition: m.pkg_id <= q.pkg_id AND m.pkg_id >= q.pkg_id instead of mere m.pkg_id = q.pkg_id. This is required for the index to be used efficiently.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜