I assume that you want the largest col2
for each col1
:
SELECT tm.* FROM ( SELECT DISTINCT col1 FROM table1 WHERE col3 = 'X' ) t JOIN table tm ON id = ( SELECT id FROM table1 ti WHERE ti.col3 = 'X' AND ti.col1 = t.col1 ORDER BY col2 DESC LIMIT 1 ) col2 ORDER BY col2 DESC
Create an index on (col3, col1, col2)
so that it works quickly.
Update:
If you only need these two columns, the query can really be simplified:
SELECT col1, MAX(col2) AS maxcol2 FROM table1 WHERE col3 = 'X' GROUP BY col1 ORDER BY maxcol2 DESC
But if you need the entire record (along with the additional fields contained in the table), you will need the original syntax.
source share