Jump to content

Selecting highest version number


Drongo_III

Recommended Posts

Hi Guys

 

I'm a bit stuck on a query and hoping someone can help. I'm sure this has a really simple solution.

 

Below is a simplified representation of a table and I'm trying to select all of the data but where there are instances of the same postID I want to only select the row with the highest version number.

 

So for instance in a select all on the table below I would expect to get IDs of 2,3 and 4.

 

 

id | postID | version
1     2           1
2     2           2
3     1           1
4     3           1
 

Any help is much appreciated. 

Link to comment
https://forums.phpfreaks.com/topic/290426-selecting-highest-version-number/
Share on other sites

Use a sub query to get the number of the most recent, then use that to join to the original table, or in your where clause condition.

Eg:

SELECT
  *
FROM table 
INNER JOIN (SELECT PostId, MAX(version) as version FROM table GROUP BY PostID) mr ON mr.PostId=table.PostId AND mr.version=table.version

Make sure you have an index on PostId,Version

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.