2017-03-01 38 views
0

首先我搜索了這個話題,我發現了一些相同話題的線索,但我不知道如何將它應用到我的方案:/排序MySQL的另一個表中的數據選擇

我有2個表即涉及這個查詢。

Table : Discussions   Table : Comments 
--------------------   ------------------------------------- 
|id | content  |   | id | d_id | content | timestamp | 
--------------------   ------------------------------------- 
| 1 | Text String |   | 1 | 2 | Comment 1 | timestamp | 
| 2 | Text String |   | 2 | 3 | Comment 2 | timestamp | 
| 3 | Text String |   | 3 | 4 | Comment 3 | timestamp | 
| 4 | Text String |   | 4 | 2 | Comment 4 | timestamp | 
| 5 | Text String |   | 5 | 3 | Comment 5 | timestamp | 
--------------------   ------------------------------------- 

現在我需要從討論表中的ID &需要使用對它進行排序按照Unix時間戳的註釋表D_ID

因此,最近評論的討論將首先在網站上列出。

希望你有想法。請告訴我如何爲此編寫SQL查詢。

+0

您還應該向我們展示您的預期輸出。這看起來像你應該加入'Discussions.id = Comments.d_id'上的兩個表格,但是不清楚你想要如何或想要分類什麼。 –

回答

0

如果我明白你的問題很好,那麼你需要連接兩個表

select Comments.d_id, Discussions.content as d_content, Comments.content as c_content 
from Comments 
join Discussions 
on Discussions.id = Comments.d_id 
order by Discussions.id, Comments.timestamp 

編輯:

select Comments.d_id, Discussions.content as d_content, Comments.content as c_content 
from Comments 
right join Discussions 
on Discussions.id = Comments.d_id 
order by Discussions.id, Comments.timestamp 
+0

如果沒有與最近發佈的討論相關的評論,會發生什麼? –

+0

@ShyaminAyesh它不會成爲結果。如果您仍想在結果中查看這些記錄,則可能需要使用正確的連接。 –

+0

請問如何正確使用?我以前嘗試與左連接,但它沒有工作?你可以發佈左連接的查詢嗎? –

0

一個簡單的加入將分別討論多次取(如評論數討論有)。 此查詢將返回在每次討論最多一次:

SELECT d_id FROM Comments GROUP BY d_id ORDER BY MIN(timestamp) DESC 

當然,如果你想要更多的數據,而不僅僅是Discussions.id,你就必須做一些連接。

還要注意,此查詢不會返回沒有任何評論的討論ID。爲此你也必須加入。

相關問題