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
精彩评论