2009-07-07 137 views
2

我的最新數據2項每個類別如下所示:如何獲得一個選擇(與MySQL)

 
id|category|insertdate|title.... 
-------------------------------- 
1|1|123|test 1 
2|1|124|test 2 
3|1|125|test 3 
4|2|102|test 4 
5|2|103|test 5 
6|2|104|test 6 

我試圖做到的是獲取最新的2項按類別(如以通過insertdate DESC),所以結果應該是:

 
id|.... 
---- 
3|.... 
2|.... 
6|.... 
5|.... 

獲得通過group by容易最新的,但如何獲得最新的2,而無需啓動多個查詢?

感謝您的幫助;-)
S.

回答

3

在這裏,你去哥們!

SET @counter = 0; 
SET @category = ''; 

SELECT 
    * 
FROM 
(
    SELECT 
     @counter := IF(data.category = @category, @counter+1, 0) AS counter, 
     @category := data.category, 
     data.* 
    FROM 
    (
     SELECT 
      * 
     FROM test 
     ORDER BY category, date DESC 
    ) data 
) data 
HAVING counter < 2 
+0

這應該是一個WHERE計數器<2而不是,但比它是一個理想的答案,如果有可能低效的,因爲它要經過每一條記錄等。 – Welbog 2009-07-07 12:37:53

+0

我試圖在第二個子查詢中使用HAVING,但是計數器「尚未設置在此時」或「優化器在@counter之前執行了該操作」......因此,WHERE當然也會在外部執行該任務一。 – 2009-07-07 12:39:52

0

你不會是能夠做到這種查詢在一個SELECT語句,但你可以在返回一個存儲過程把它包起來一個數據集通過將子查詢的結果添加到每個類別的臨時表中,然後返回臨時表的內容。

僞代碼:

Create a temp table 
For each distinct category, 
    Add the last two records to the temp table 
Return the temp table 

最終你會用你到底想要的一組數據,而且從應用程序的角度只有一個查詢製成。

0

另一種方法是使用group_concat獲取有序列表。如果你有大量的數據,這真的不會有任何用處。

select group_concat(id order by insertdate desc separator ','), category from tablename group by category 

或使用子查詢(這在MySQL)

select category, 
    (select id from test as test1 where test1.category = test.category order by insertdate desc limit 0,1) as recent1, 
    (select id from test as test1 where test1.category = test.category order by insertdate desc limit 1,1) as recent2 
from test 
group by category; 

我知道第二個選項是不是技術上的一個選擇,因爲有子查詢,但它是我能看到這樣做的唯一途徑它。

0
SELECT * 
FROM category AS c1 
WHERE (
    SELECT COUNT(c2.id) 
    FROM category AS c2 
    WHERE c2.id = c1.id AND c2.insertdate > c1.insertdate 
) < 2