mysql提取具有最大值的行

时间:2013-03-19 16:18:55

标签: mysql distinct max

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

数据库表:

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

我想DISTINCT cat ... WHERE user=5MAX time个值。我该如何以有效的方式做到这一点?

1 个答案:

答案 0 :(得分:2)

您需要使用带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。我使用子查询来确保每个id行返回的max(time)值是正确的id。