联接3个表(或交叉联接?)并输出2倍的user.name值

时间:2018-11-02 17:22:58

标签: sql postgresql sqlite

我正在尝试加入3个表-用户,帖子和评论,以获取诸如帖子标题,帖子作者,评论标题,评论作者之类的价值。

users (id, name)
posts (id, content, user_id)
comments (content, user_id, post_id)

现在我有查询:

SELECT posts.id AS POST_ID, posts.content AS Post, posts.user_id AS PostAuthorID,
users.name AS PostAuthorName,
comments.content AS comment, comments.user_id AS CommentsAuthorID
FROM posts
JOIN users on users.id = posts.user_id
JOIN comments ON users.id = comments.post_id;

我的问题是如何获取每个评论的作者姓名以及如何获得帖子的作者?现在通过JOIN users on users.id = posts.user_id做我有帖子作者,但是如何处理评论作者的名字呢?当我尝试向上一次联接添加其他条件时-JOIN comments ON users.id = comments.post_id AND users.id = comments.user_id,我收到的表中包含由同一用户创建的帖子和评论。欢迎任何帮助。

3 个答案:

答案 0 :(得分:0)

user (user_id, name)
post (post_id, user_id, descrition)
comment (cm_id, post_id, content)
you join  user with post by user_id and post with comment by post_id

答案 1 :(得分:0)

Select comments.user_id AS CommentsAuthorID
Where posts.id = x
From (posts left join comments on posts.id = comments.post_id

如果您只需要评论。user_id可以加入帖子和评论。

当您需要comment.users.name时,查询将是:

Select comments.user_id AS CommentsAuthorID comments.users_name AS UserName 
Where posts.id = x
From (posts left join comments on posts.id = comments.post_id

答案 2 :(得分:0)

我很确定你的意思是

ON posts.id = comments.post_id;

您的查询当前显示的位置:

ON users.id = comments.post_id;

然后只需两次加入users

SELECT p.id AS post_id, p.content AS post, p.user_id AS post_author_id
     , pu.name AS post_author_name
     , c.content AS comment, c.user_id AS comment_author_id
     , cu.name AS comment_author_name
FROM posts    p
JOIN users    pu ON pu.id = p.user_id
JOIN comments c  ON c.post_id = p.id
JOIN users    cu ON cu.id = c.user_id;

为带有多个评论的帖子返回多行。每个评论一个。对于没有评论的帖子,返回什么。要包含没有评论的帖子(或者如果任何ID列可以为NULL),请使用LEFT JOIN代替...