根据表B中的值从表A中选择值?

时间:2016-10-24 07:13:32

标签: mysql sql

我正在创建一个非常基本的发布和回复系统,以便更好地理解MySQL和PHP。我有两个表:帖子和评论。

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

我想要做的是通过最近回复的帖子来订购帖子。所以我需要SELECT * from posts ordered by comments.timestamp desc,因为我想通过最近的评论而不是原始帖子的时间戳来订购。我无法弄清楚一个有效的查询。

3 个答案:

答案 0 :(得分:0)

你可能正在寻找这个

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

答案 1 :(得分: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 );

答案 2 :(得分:-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