Jump to content

Selecting highest version number


Drongo_III
Go to solution Solved by kicken,

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
Share on other sites

  • Solution

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
  • Like 1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.