Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing the record with the highest value for one column in a single query?

I have a table that looks something like this:

| id | fk1 | fk2 | version |
|  1 |  1  |  1  |    1    |
|  2 |  1  |  1  |    2    |
|  3 |  1  |  1  |    3    |

Having on hand the values of fk1 and fk2 I am trying to get the record with the highest value for version. Currently what I am doing is this:

version = Project.where("fk1= ? AND fk2= ?", params.require(:fk1), params.require(:fk2)).maximum(:version)
@project = Project.find_by_fk1_and_fk2_and_version(params.require(:fk1), params.require(:fk2), version)

This gets me the correct record, but I have to execute 2 queries for something that seems really simple in theory, but after trying a number of different things I had no luck with doing this with a single query. I am envisioning something like:

version = Project.where("fk1= ? AND fk2= ? AND max(version)", params.require(:fk1), params.require(:fk2))

or something.

like image 259
bpromas Avatar asked Nov 21 '25 14:11

bpromas


1 Answers

Well the rails way to do that is

Project.where(fk1: params.require(:fk1), fk2: params.require(:fk2)).
  order('version desc').first

Which translates to an sql query like:

SELECT * FROM projects WHERE fk1 = "fk1" AND fk2 = "fk2" ORDER BY version DESC LIMIT 1;
like image 153
xlembouras Avatar answered Nov 23 '25 02:11

xlembouras



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!