Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

MySQL: Select rows with highest value in a column only

Posted on 2009-03-29
2
Medium Priority
?
1,252 Views
Last Modified: 2013-12-12
Hello,

I want to fetch rows with the highest value in a column.
With this table contents given:

ID --- VERSION --- text
1  --- 1              --- abc
1  --- 2              --- def
1  --- 3              --- ghj
2  --- 1              --- mno
3  --- 1              --- uvw
3  --- 2              --- xyz

I want a query that gives me

ID --- VERSION --- text
1  --- 3              --- ghj
2  --- 1              --- mno
3  --- 2              --- xyz

as result. I need a performant query, as this query will by executed quite often (possibly multiple times when visiting a page).

I startet experimenting with GROUP BY, but couldn't quite get to a working result.

I'd be glad if someone could help me on this one.
CREATE TABLE test(id INT UNSIGNED NOT NULL AUTO_INCREMENT, version SMALLINT NOT NULL DEFAULT 1, text TEXT, PRIMARY KEY(id, version));
 
INSERT INTO test(id, version, text) values(1, 1, 'abc'), (1, 2, 'def'), (1, 3, 'ghj'), (2, 1, 'mno'), (3, 1, 'uvw'), (3, 2, 'xyz');

Open in new window

0
Comment
Question by:Chakotay505
2 Comments
 
LVL 39

Accepted Solution

by:
Roger Baklund earned 2000 total points
ID: 24012595
Try this:
select test.* 
from test 
join (
  select id,max(version) as max_version 
  from test 
  group by id
) m on test.id=m.id and version=max_version;

Open in new window

0
 
LVL 3

Author Comment

by:Chakotay505
ID: 24012662
Thanks, works great.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows the steps required to install WordPress on Azure. Web Apps, Mobile Apps, API Apps, or Functions, in Azure all these run in an App Service plan. WordPress is no exception and requires an App Service Plan and Database to install
This article discusses how to implement server side field validation and display customized error messages to the client.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Suggested Courses

972 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question