gpt4 book ai didi

mysql提取具有最大值的行

转载 作者:行者123 更新时间:2023-11-29 06:50:50 26 4
gpt4 key购买 nike

我正在尝试找出从数据库中获取所需行的最佳方法。

数据库表:

id user cat time
1 5 1 123
2 5 1 150
3 5 2 160
4 5 3 100

我想用 MAX time 值获取 DISTINCT cat ... WHERE user=5。我应该如何有效地做到这一点?

最佳答案

您将希望使用带有GROUP BY 的聚合函数:

select user, cat, max(time) as Time
from yourtable
group by user, cat

参见 SQL Fiddle with Demo

如果你想包含 id 列,那么你可以使用子查询:

select t1.id,
t1.user,
t1.cat,
t1.time
from yourtable t1
inner join
(
select max(time) Time, user, cat
from yourtable
group by user, cat
) t2
on t1.time = t2.time
and t1.user = t2.user
and t1.cat = t2.cat

参见 SQL Fiddle with Demo .我使用子查询来确保随每个 max(time) 行返回的 id 值是正确的 id。

关于mysql提取具有最大值的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15504852/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com