[英]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![]() |
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
.如您所见,
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![]() |
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).从这个结果我想
SELECT
每个唯一value3
只有一次,但是value2
中值最高的那一行(无论value1
是什么)。
So expected result would be:所以预期的结果是:
value1![]() |
value2![]() |
value3![]() |
---|---|---|
bar![]() |
18 ![]() |
anything5![]() |
baz![]() |
100 ![]() |
something0![]() |
How can I do that?我怎样才能做到这一点?
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.