In my table I have two fields among others : article_id and version
Example:
article_id | version
-----------|----------
5 | 1
5 | 2
6 | 1
What I want to do is to retrieve the latest version for each article id. (In my example I want to retrieve the article 5 version 2 object and article 6 and version 1 object).
The problem is that mysql is doing the group by instead of the order by so it returns to me the FIRST version of each article, but I want the opposite.
Do you have an idea please ?
Solution
select *
from article r
where r.version=(
select max(version)
from article r2
where r2.article_id = r.article_id
);
Your question is a bit vague, but I believe is is more or less this what you want:
select * from ( select <table>.*, row_number() over (partition by article_id order by version desc) r from <table> ) where r = 1The query returns one record for each (distinct) article_id. This record is the one with the highest version for the article_id returned.
So, together with a “test case”, this can be seen in action:
which returns: