开发者

Retrieve and entry for all "type"s but only the most recent entry for each "type" from MySQL table

开发者 https://www.devze.com 2022-12-24 20:49 出处:网络
Basically if I had a mysql table with columns: id, type, content, version. There will be multiple entries wit开发者_如何学Ch the same type. Version is a number which increments with each new entry o

Basically if I had a mysql table with columns: id, type, content, version.

There will be multiple entries wit开发者_如何学Ch the same type. Version is a number which increments with each new entry of a certain type.

I want to be able to get the most recent entry of each type for all types with one query.

Is this possible or do I need to do separate queries for each type?

Cheers


SELECT  mi.*
FROM    (
        SELECT  DISTINCT type
        FROM    mytable
        ) md
JOIN    mytable mi
ON      mi.id = 
        (
        SELECT  mo.id
        FROM    mytable mo
        WHERE   mo.type = md.type
        ORDER BY
                mo.type DESC, mo.version DESC, mo.id DESC
        LIMIT 1
        )

Create an index on (type, version, id) for this to work fast.


try:

SELECT
    y.*
    FROM YourTable y
        INNER JOIN (SELECT
                        Type,MAX(Version) AS MaxVersion
                        FROM YourTable
                        GROUP BY Type
                   ) dt ON y.Type=dt.Type AND y.Version=dt.Version
0

精彩评论

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