Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid a sub-query?

Tags:

sql

mysql

This is my table:

ID   KEY    VALUE
1    alpha  100
2    alpha  500
3    alpha  22
4    beta   60
5    beta   10

I'm trying to retrieve a list of all KEY-s with their latest values (where ID is in its maximum):

ID   KEY     VALUE
3    alpha   22
5    beta    10

In MySQL I'm using this query, which is not effective:

SELECT temp.* FROM
  (SELECT * FROM t ORDER BY id DESC) AS temp
GROUP BY key

Is it possible to avoid a sub-query in this case?

like image 684
yegor256 Avatar asked Oct 28 '25 17:10

yegor256


1 Answers

Use an INNER JOIN to join with your max ID's.

SELECT  t.*
FROM    t
        INNER JOIN (
          SELECT  ID = MAX(ID)
          FROM    t
          GROUP BY
                  key
        ) tm ON tm.ID = t.ID                  

Assuming the ID column is indexed, this is likely as fast as its going to get.

like image 200
Lieven Keersmaekers Avatar answered Oct 31 '25 06:10

Lieven Keersmaekers



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!