2013-03-19 46 views
1

我想弄清楚從數據庫中獲取所需行的最佳方法。mysql提取最大值的行

數據庫表:

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值。我應該如何有效地做到這一點?

回答

3

你將要使用的聚合函數具有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。

+0

輝煌,第一個例子適合我:)謝謝! – fshock 2013-03-19 16:31:00

+0

@fshock很高興它的作品! :) – Taryn 2013-03-19 16:33:14