简体   繁体   English

如何在一个查询中从用户,帖子,评论表中获取结果

[英]How to fetch results from user,post,comments tables in one query

The title may not be the fit to the question perfectly ! 标题可能不完全适合这个问题! pardon me 对不起

Goal 目标

I want to achieve the name of the user who has done a post ,the description of that post( p_description ), the comments that are there on that post ,and the name of those who has provided comments ( comment_description ) 我要实现的name中的user谁做了post ,将description该职位(的p_description ),是那里的意见post ,如果谁提供意见的名称( comment_description

How can I achieve that ? 我怎样才能做到这一点?

I've three tables: 我有三张桌子:

user

post and post

comments

User table is like : 用户表如下:

u_id name and so... u_id name等......

Post table, here it is : 邮政表,这里是:

u_id p_id p_description u_id p_id p_description

u_id as foreign key from user table , u_id作为user表的外键,

and the Comments table is: Comments表是:

u_id p_id comment_description . u_id p_id comment_description

note that the u_id and p_id in table comments are both as foreign keys from table user and post respectively. 请注意,表注释中的u_idp_id分别是表userpost外键。

I'm writing the following query for the above Goal : 我正在为上述目标编写以下查询:

SELECT p_description,f_name,comment_description as COMMENT FROM user JOIN post ON user.u_id = post.u_id JOIN comments ON user.u_id = comments.u_id

It gives me the post description , name of that guy who has done post , and the comments on that post , and I want to have also the name of those guys who has done comments to that post. 它给了我post description ,发post description name of that guy who has done post ,以及the comments on that post name of that guy who has done post the comments on that post ,我想也有那些对那篇文章做过评论的人的名字

If the problem is not explained well. 如果问题没有得到很好的解释。

simply I want query for the above GOAL regarding those three tables. 我只想查询关于这三个表的上述目标

Join user once more on the user ID in comments . comments再次加入user ID。

SELECT u1.name,
       p1.p_description,
       u2.name,
       c1.comment_description
       FROM user u1
            INNER JOIN post p1
                       ON u1.u_id = p1.u_id
            INNER JOIN comments c1
                       ON c1.p_id = p1.p_id
            INNER JOIN user u2
                       ON u2.p_id = c1.p_id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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