简体   繁体   中英

Select values from table A based on values from table B?

I'm creating a very basic post and reply system to get a better understanding of MySQL and PHP. I have two tables: posts and comments.

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

What I want to do is order the posts by the ones that have the most recent reply. So I would need to SELECT * from posts ordered by comments.timestamp desc since I want to order by most recent comments and not by the original post's timestamp. I can't figure out a proper query that works.

You may looking for this

SELECT  p.* 
FROM  posts p 
INNER JOIN comments c ON c.post_id= p.post_id
ORDER BY c.timestamp desc
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 );
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM