在 MySQL 中用 MAX() 过滤两次
Filter twice with MAX() in MySQL
我在 MySQL 5.7
数据库中有以下名为 my_values
的 table:
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
如您所见,value1
中有重复项。我只想 SELECT
每个唯一 value1
一次,但在 value2
.
中具有最高值的那一行
我为此使用此查询:
SELECT v.* FROM my_values v WHERE v.value2 = (SELECT MAX(v2.value2) FROM my_values v2 WHERE v2.value1 = v.value1);
结果是:
value1
value2
value3
foo
12
anything5
bar
18
anything5
baz
100
something0
从这个结果我想 SELECT
每个唯一的 value3
只一次,但是 value2
中具有最高值的那一行(不管 value1
是什么) .
所以预期的结果是:
value1
value2
value3
bar
18
anything5
baz
100
something0
我该怎么做?
这里是你如何做到的:
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
您可以使用元组进行比较:
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
);
我在 MySQL 5.7
数据库中有以下名为 my_values
的 table:
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 |
如您所见,value1
中有重复项。我只想 SELECT
每个唯一 value1
一次,但在 value2
.
我为此使用此查询:
SELECT v.* FROM my_values v WHERE v.value2 = (SELECT MAX(v2.value2) FROM my_values v2 WHERE v2.value1 = v.value1);
结果是:
value1 | value2 | value3 |
---|---|---|
foo | 12 | anything5 |
bar | 18 | anything5 |
baz | 100 | something0 |
从这个结果我想 SELECT
每个唯一的 value3
只一次,但是 value2
中具有最高值的那一行(不管 value1
是什么) .
所以预期的结果是:
value1 | value2 | value3 |
---|---|---|
bar | 18 | anything5 |
baz | 100 | something0 |
我该怎么做?
这里是你如何做到的:
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
您可以使用元组进行比较:
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
);