2013-05-21 41 views
0

如何從php mysql中的每個類別獲取第二篇文章?mysql - 從每個類別中選擇第二個博客

如果我有一個表如下:

post_id | cate_id 
-------------------- 

    1  |  2 
    2  |  4 
    3  |  2 
    4  |  1 
    5  |  1 
    6  |  3 
    7  |  4 
    8  |  3 
    9  |  5 
    10 |  5 

期待的結果如下:

post_id | cate_id 
-------------------- 

    5 |  1 
    3 |  2 
    8 |  3 
    7 |  4 
    10 |  5 

感謝。

回答

0
SELECT MAX(post_id) post_ID, cate_id 
FROM table1 
GROUP BY cate_id 
+0

而這項工作當前的例子。不幸的是,這不會得到OP想要的。考慮每個'cate_id'有10個職位。與您的查詢,你會得到最後的職位,而不是第二個職位。 –

+0

謝謝。我試過這個。它是選擇第二個最大的帖子,但我想從每個類別ID獲得第二個記錄。 –

1
select t.cate_id,min(t.post_id) 
from (select cate_id, min(post_id) post_id from foo group by 1) firsts 
inner join foo t on t.cate_id=firsts.cate_id and t.post_id > firsts.post_id 
group by 1; 

考慮:

mysql> select cate_id, group_concat(post_id order by post_id) from foo group by 1; 
+---------+----------------------------------------+ 
| cate_id | group_concat(post_id order by post_id) | 
+---------+----------------------------------------+ 
|  0 | 0,1,3,4,7        | 
|  1 | 0,1,2,4,6,8,9       | 
|  3 | 7,11         | 
|  4 | 2,3         | 
|  5 | 1,3,9         | 
|  6 | 0,2,5,6,7,8,9       | 
|  7 | 0,2         | 
|  8 | 0,1,4,6,7,8,9       | 
|  9 | 1,2         | 
+---------+----------------------------------------+ 

生產:

mysql> select t.cate_id,min(t.post_id) from (select cate_id, min(post_id) post_id from foo group by 1) firsts inner join foo t on t.cate_id=firsts.cate_id and t.post_id > firsts.post_id group by 1; 
+---------+----------------+ 
| cate_id | min(t.post_id) | 
+---------+----------------+ 
|  0 |    1 | 
|  1 |    1 | 
|  3 |    11 | 
|  4 |    3 | 
|  5 |    3 | 
|  6 |    2 | 
|  7 |    2 | 
|  8 |    1 | 
|  9 |    2 | 
+---------+----------------+ 
相關問題