2016-09-07 67 views
0

所以,我有一個表,線程拉論壇線程最新帖子的順序

ThreadNumber | Sticky | Title 
1   | 1  | Read This Before Posting! 
2   | 0  | Second Topic 
3   | 0  | Check This  

而第二個表,帖子

ThreadNumber | Author | Timestamp | Body      | PostNumber 
1   | User1 | 1   | Read up!     | 0 
1   | User2 | 2   | I see.      | 1 
2   | User2 | 3   | So tell me what'chu want! | 0 
3   | User3 | 5   | Yeah, check this out.  | 0 
2   | User3 | 7   | What'chu really really want!| 1 
2   | User1 | 10  | I'll tell you what I want! | 2 

(時間戳在帖子是十 - 當給定的用戶向db提交它們的評論時,PHP time()函數給出的時間的第二個整數時間表示。)因此,當涉及到在f上顯示所有論壇主題主題時orum概述頁面,我想要做的是按照發布上次評論的順序顯示所有主題。我在嵌套的MySQL查詢中嘗試過自己的手(沒有解決),所以我開始嘗試做一些研究。我找到的其他東西都無法找到我想要的東西。我覺得this接近,但我仍然得到了唯一的ThreadNumbers給出的所有結果。理想情況下,我會得到返回的是一樣的東西:

ThreadNumber | Title      | LastTimestamp 
2   | Second Topic    | 10 
3   | Check This    | 5 
1   | Read This Before Posting! | 1 

由於一噸讀這篇文章,任何可能的[和急需]求助!

我已經試過

不僅不會回到我其實是想
SELECT PostNumber, ThreadNumber, Body, Author, Timestamp 
FROM (SELECT PostNumber, ThreadNumber, Body, Author, Timestamp 
     FROM Posts 
     ORDER BY Timestamp DESC) AS p 
GROUP BY ThreadNumber; 

,但沒有工作,我打算反正的方式。

+0

您可以使用迄今爲止嘗試過的查詢來更新您的問題嗎? – Maximus2012

+0

將'last_post_id'字段添加到'threads'表中。 – zerkms

+0

@ Maximus2012已添加。 –

回答

0

您可以將以下做,在一個請求通過下面的例子

select 
    Posts.ThreadNumber, 
    Title, 
    max(Timestamp) 
from Threads 
left join Posts on Threads.ThreadNumber = Posts.ThreadNumber 
group by Posts.ThreadNumber, Title 
order by max(timestamp) desc; 

隨着源數據,如

mysql> select * from Posts; 
+--------------+--------+-----------+------+------------+ 
| ThreadNumber | Author | Timestamp | Body | PostNumber | 
+--------------+--------+-----------+------+------------+ 
|   1 | User1 |  20 |  |   0 | 
|   2 | User1 |  30 |  |   0 | 
|   3 | User1 |  10 |  |   0 | 
|   1 | User1 |  24 |  |   0 | 
|   2 | User1 |   2 |  |   0 | 
|   3 | User1 |  200 |  |   0 | 
+--------------+--------+-----------+------+------------+ 
6 rows in set (0,00 sec) 

mysql> select * from Threads; 
+--------------+--------+----------+ 
| ThreadNumber | Sticky | Title | 
+--------------+--------+----------+ 
|   1 |  0 | Thread 1 | 
|   2 |  0 | Thread 2 | 
|   3 |  0 | Thread 3 | 
+--------------+--------+----------+ 
3 rows in set (0,00 sec) 

將輸出

mysql> select distinct Posts.ThreadNumber, Title, max(Timestamp) from Threads left join Posts on Threads.ThreadNumber = Posts.ThreadNumber group by Posts.ThreadNumber, Title order by max(timestamp) desc; 
+--------------+----------+----------------+ 
| ThreadNumber | Title | max(Timestamp) | 
+--------------+----------+----------------+ 
|   3 | Thread 3 |   200 | 
|   2 | Thread 2 |    30 | 
|   1 | Thread 1 |    24 | 
+--------------+----------+----------------+ 
3 rows in set (0,00 sec) 

但在你的情況下,我會重新開發數據庫結構。你的結構中有一些非常糟糕的問題。至少你可以在帖子中添加id字段。目前,您無法在其中設置有效的索引,並且您的請求會因大數據而變慢。

+0

爲什麼你在這裏需要'獨特'? – zerkms

+0

是的,實際上這裏沒有任何意義。 – Spell

相關問題