简体   繁体   English

在 MySQL 中使用 MAX() 过滤两次

[英]Filter twice with MAX() in MySQL

I have the following table called my_values in a MySQL 5.7 database:我在MySQL 5.7数据库中有名为my_values的下表:

value1价值1 value2价值2 value3价值3
foo 7 7 something4某事4
foo 5 5 something1某事1
foo 12 12 anything5任何东西5
bar酒吧 3 3 something7某事7
bar酒吧 18 18 anything5任何东西5
bar酒吧 0 0 anything8任何东西8
baz巴兹 99 99 anything9任何东西9
baz巴兹 100 100 something0某事0

As you see, there are duplicates in value1 .如您所见, value1中有重复项。 I want to SELECT each unique value1 only once, but that row with the highest value in value2 .我只想SELECT每个唯一value1一次,但是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价值1 value2价值2 value3价值3
foo 12 12 anything5任何东西5
bar酒吧 18 18 anything5任何东西5
baz巴兹 100 100 something0某事0

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).从这个结果我想SELECT每个唯一value3只有一次,但是value2中值最高的那一行(无论value1是什么)。

So expected result would be:所以预期的结果是:

value1价值1 value2价值2 value3价值3
bar酒吧 18 18 anything5任何东西5
baz巴兹 100 100 something0某事0

How can I do that?我怎样才能做到这一点?

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小提琴

You can use tuples for the comparison:您可以使用元组进行比较:

select t.*
from my_values t
where (t.value2, t.value3) = (select t2.value2, t2.value3
                              from my_values t2
                              where t2.value1 = t.value1
                              order by t2.value2 desc, t2.value3 desc
                              limit 1
                             );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM