2014-02-05 176 views
0

我有一箇舊的論壇上,我很多年前建立了一個我成了網站上的只讀部分。作爲編程練習我試圖削減的代碼儘管可怕數據庫設計中使用的量。MYSQL連接查詢結果

我試圖實現的是在回覆頁面上:單個查詢顯示第一篇文章(愚蠢地存儲在'主題'表格中),然後是'回覆表格中的其他帖子。

刪節表:

'replies' 
topicID 
posted_by 
body 
date_posted 

'topics' 
topicID 
subject 
body 
posted_by 
date_posted 

我試圖讓形式爲:

從後面回覆「主題」最初發表date_posted排序(最早的第一)。

這裏是我一直在擺弄與查詢:

SELECT DISTINCT 
r.body, r.posted_by, r.date_posted, t.body, t.date_posted, t.posted_by, t.subject 
FROM 
replies r 
LEFT JOIN topics t 
    ON r.topicID = t.topicID 
WHERE 
r.topicID = 2372 
ORDER BY 
t.posted_by DESC, 
r.date_posted DESC 

有沒有人有關於如何調整這讓我期望的方案什麼想法?

回答

1

聯合查詢應該提供你正在尋找的數據:

SELECT topicID, subject, body, posted_by, date_posted 
FROM topics 
WHERE topicID = 2372 
UNION 
SELECT r.topicID, t.subject, r.body, r.posted_by, r.date_posted 
FROM replies r 
    INNER JOIN topics t ON r.topicID = t.topicID 
WHERE t.topicID = 2372 
ORDER BY r.date_posted DESC; 
+0

您好,感謝,這是極好的。它做了我想要的幾乎所有東西。直到出現錯誤的'ORDER BY'。我與它擺弄,看看我能做些什麼:) 編輯:我只是放棄了'r.'別名,它的工作^^ –

+1

哎呀,很抱歉。作爲替代方案,你可以換用括號聯合查詢的第二部分,以的種類僅適用於答覆。 –