I have a MySQL table structured somewhat like this:
type name value
=====================
1 item1 1
1 item2 20
2 item3 0
3 item4 5
3 item5 2
3 item6 50
I need to write a query that returns the lowest valued item of each type, sorted by the value. So the result should be:
type name value
=====================
2 item3 0
1 item1 1
3 item5 2
I can get this to work, but it’s looking really, really ugly right now. Is there an elegant way to do this?
Thanks so much!
This is called a “greatest-n-per-group” query (under that tag on SO you will find many similar questions). (I know you want the “lowest-n-per-group”, but it’s the same problem).
Usually, you would be able to do:
But this won’t work if you also want the
namecorresponding to theMIN(value).To retrieve the minimum
valuepertypeand also the corresponding row, you join your table to itself withintype(theGROUP BY) variable, and with a sorting condition onvalue(theMIN) variable:Note :
LEFT JOINmytableto itself, restricting the join such that all thetypes are the same. This will produce a table with every combination of values for each type.LEFT JOINto restrict the combinations of values such thatt1.value > t2.value. So now we have a table with every combination of values within each type, but t1’s is bigger than t2’sLEFT JOIN, if there is at1.valuefor which there is no smallert2.value, the correspondingt2columns will be NULL. But this is precisely the smallestt1.valuefor that type!WHERE t2.value IS NULLcondition in to pick out exactly these rows.