Search code examples
mysqlsqlsql-max

Filter twice with MAX() in MySQL


I have the following table called my_values in a MySQL 5.7 database:

value1 value2 value3
foo 7 something4
foo 5 something1
foo 12 anything5
bar 3 something7
bar 18 anything5
bar 0 anything8
baz 99 anything9
baz 100 something0

As you see, there are duplicates in value1. I want to SELECT each unique value1 only once, but that row with the highest value in value2.

I'm using this query for that:

SELECT v.* FROM my_values v WHERE v.value2 = (SELECT MAX(v2.value2) FROM my_values v2 WHERE v2.value1 = v.value1);

The result is:

value1 value2 value3
foo 12 anything5
bar 18 anything5
baz 100 something0

Here's a fiddle of that.

From this result I want to SELECT each unique value3 only once, but that row with the highest value in value2 (no matter what value1 is).

So expected result would be:

value1 value2 value3
bar 18 anything5
baz 100 something0

How can I do that?


Solution

  • here is how you can do it :

    select t1.*
    from my_values t1
    natural join (select value1, MAX(value2) value2
                   from my_values 
                   group by value1 ) t2
    natural join (select value3, MAX(value2) value2
                   from my_values 
                   group by value3) t3
    

    fiddle