Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 根据表B中的值从表A中选择值?_Mysql_Sql - Fatal编程技术网

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

Mysql 根据表B中的值从表A中选择值?,mysql,sql,Mysql,Sql,我正在创建一个非常基本的帖子和回复系统,以便更好地理解MySQL和PHP。我有两个表格:帖子和评论 posts(post_id, post_user, timestamp, post_text) comments(comment_id, post_id, timestamp, comment_text) 我想做的是按最新回复的帖子排序。所以我需要从comments.timestamp desc排序的帖子中选择*,因为我想按最近的评论排序,而不是按原始帖子的时间戳排序。我想不出一个合适的查询是否

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

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

我想做的是按最新回复的帖子排序。所以我需要
从comments.timestamp desc排序的帖子中选择*,因为我想按最近的评论排序,而不是按原始帖子的时间戳排序。我想不出一个合适的查询是否有效

你可能在找这个

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

只有通过时间戳,你才能做到这一点,为什么你不想使用时间戳?如果你提供示例数据和预期输出,这会很有帮助。请参见“更好地理解MySQL…”我不知道为什么会有反对票,但这很接近,但并不正确。它多次显示同一原始帖子,但不显示帖子表中的所有帖子。不过,它确实更新了帖子,最新的评论在上面。
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
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 );