我正试图找出从数据库中获取所需行的最佳方法。
数据库表:
id user cat time
1 5 1 123
2 5 1 150
3 5 2 160
4 5 3 100
我想DISTINCT cat ... WHERE user=5
取MAX time
个值。我该如何以有效的方式做到这一点?
答案 0 :(得分:2)
您需要使用带GROUP BY
的聚合函数:
select user, cat, max(time) as Time
from yourtable
group by user, cat
如果要包含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。