我是 sql 新手。我有两个连接表,它是帖子表帖子和评论,我正在使用 MySql。
Post :
id, UserName, Phone , product
Comments:
id , CommentText, post_id
我正在使用联接查询来加入它们
SELECT t1.UserName , t1.Phone, t2.Comments
FROM table1 AS t1
LEFT JOIN table2 AS t2 ON (t1.id = t2.follow_id )
现在我需要显示所有唯一用户及其最后的评论,所以它们看起来像这样
1. User1 LastComment1
2. User2 LastComment2
3. User3 LastComment3
...
我将非常感谢您的帮助。
最佳答案
我假设两个表中的列 id 都是 AUTO_INCRMENT PRIMARY KEY。
这个相关子查询将为您提供正确的答案。
查询
SELECT
Post.Username
, Post.Phone
, (SELECT
Comments.CommentText
FROM
Comments
WHERE
Comments.post_id = Post.id
ORDER BY
Comments.id DESC
LIMIT 1
)
AS LastComment
FROM
Post
您可能需要在 Comments.post_id 上添加索引以提高此查询的性能。
关于mysql - 从帖子sql中获取最新的用户评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48646761/