2016-10-24 90 views
3

我正在創建一個非常基本的帖子和回覆系統,以更好地理解MySQL和PHP。我有兩個表格:帖子和評論。根據表B的值從表A中選擇值?

posts(post_id, post_user, timestamp, post_text) 
comments(comment_id, post_id, timestamp, comment_text) 

我想要做的是按最近有答覆的人排序。所以我需要SELECT * from posts ordered by comments.timestamp desc,因爲我想按最近的評論排序,而不是原帖的時間戳。我無法弄清楚正確的查詢是否有效。

+0

只有時間戳你可以這樣做,爲什麼你不想使用時間戳? – YLS

+0

如果您提供樣本數據和您的預期輸出將會有幫助 –

+0

請參閱http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-我是一個非常簡單的sql查詢 – Strawberry

回答

0

你可能在找這個

SELECT p.* 
FROM posts p 
INNER JOIN comments c ON c.post_id= p.post_id 
ORDER BY c.timestamp desc 
+0

關心評論下來選民爲什麼倒票? –

+0

我不知道爲什麼downvotes,但這是接近但不正確的。它會多次顯示相同的原始帖子,並且不會在帖子表中顯示每個帖子。它不更新到帖子,但最新的評論是最重要的。 – FreeBird85x

-1
SELECT A.Post_Id FROM 
(SELECT P.Post_Id,C.TimeStamp,ROW_NUMBER() OVER(PARTITION BY S.Post_Id ORDER BY C.TimeStamp DESC) Rnk FROM POSTS p INNER JOIN COMMENTS C 
ON P.Post_Id=C.Post_Id) A 
WHERE A.Rnk=1 
ORDER BY A.TimeStamp DESC 
This is SQL SERVER version. 
So hope you can find Mysql version for it 
+0

「以更好地理解MySQL ......」 – Strawberry

0
SELECT post_id, post_user, timestamp, post_text, 
     most_recent_comment 
    FROM posts NATURAL JOIN 
     (SELECT post_id, 
       MAX(timestamp) AS most_recent_comment 
      FROM comments 
     GROUP 
      BY post_id) AS t 
UNION 
SELECT post_id, post_user, timestamp, post_text, 
     NULL AS most_recent_comment 
    FROM posts 
WHERE post_id NOT IN (SELECT post_id FROM comments); 
相關問題