2011-02-10 48 views
1

我在MySQL/SQL一個新手,我有一個表是這樣的:獲取所有的最近的2項,但是從2個不同的類別

id | cat | datetime | ....... 10 more columns 
10 | 20 | 10-12-31 00:00 | ..... 
64 | 12 | 10-10-25 10:00 | ..... 
39 | 12 | 10-11-21 08:00 | ..... 
21 | 20 | 10-12-30 20:00 | ..... 
95 | 21 | 10-09-16 00:00 | ..... 

查詢的結果將是:

id | cat | datetime | ....... 10 more columns 
10 | 20 | 10-12-31 00:00 | ..... 
39 | 12 | 10-11-21 08:00 | ..... 

我都試過,但它不工作(我知道它不會):

SELECT *, max(datetime) FROM table GROUP BY cat LIMIT 2 

回答

1
SELECT id, cat, datetime, ... 
FROM `table` 
    INNER JOIN (
    SELECT cat, MAX(datetime) AS mdate 
    FROM `table` 
    GROUP BY cat 
    ORDER BY mdate DESC 
    LIMIT 2 
) AS t 
    ON `table`.cat = t.cat AND `table`.datetime = t.mdate; 

可能有更有效的方法,但這會起作用。

+0

您需要`訂購mdate DESC` – ajreal 2011-02-10 15:16:36

相關問題