MySQL查询 - 选择帖子的所有评论

时间:2015-03-08 14:49:26

标签: php mysql sql facebook

我有这些表格:

tbl_posts:

+---------------+------------------+------+-----+---------+----------------+
| Field         | Type             | Null | Key | Default | Extra          |
+---------------+------------------+------+-----+---------+----------------+
| id            | int(10)          | NO   | PRI | NULL    | auto_increment |
| date          | varchar(10)      | NO   |     | NULL    |                |
| content       | text             | NO   |     | NULL    |                |
| status        | tinyint(1)       | NO   |     | NULL    |                |
| person_id     | int(10)          | NO   |     | NULL    |                |
+---------------+------------------+------+-----+---------+----------------+

tbl_comments:

+---------------+------------------+------+-----+---------+----------------+
| Field         | Type             | Null | Key | Default | Extra          |           
+---------------+------------------+------+-----+---------+----------------+
| id            | int(10)          | NO   | PRI | NULL    | auto_increment |
| comment       | varchar(10)      | NO   |     | NULL    |                |
| post_id       | int(10)          | NO   |     | NULL    |                |
| person_id     | int(10)          | NO   |     | NULL    |                |
+---------------+------------------+------+-----+---------+----------------+

和tbl_person,其中包含person_id和其他一些字段......

我想选择某个人发布的所有帖子以及每个帖子的所有评论(就像facebook一样)

我尝试了这个查询,但它只为我发了一条评论

select * from tbl_posts right join tbl_comments on tbl_posts.id = tbl_comments.post_id join tbl_person on tbl_person.id = tbl_posts.Person_id and tbl_comments.Person_id = 3 group by tbl_comments.id

2 个答案:

答案 0 :(得分:0)

如果您的外键设置正确,inner join应该没问题。而且,您不需要group by

select *
from tbl_posts join
     tbl_comments
     on tbl_posts.id = tbl_comments.post_id join
     tbl_person
     on tbl_comments.Person_id = 3;

实际上,我怀疑问题是tbl_person.id = tbl_posts.Person_id。您的查询仅返回评论自己帖子的人。

答案 1 :(得分:0)

连接表时,应始终确保要加入的表之间存在关系。在您的情况下,这应该为您提供由某个人发布的所有帖子以及每个帖子的所有评论:

SELECT *
FROM tbl_posts 
LEFT JOIN
tbl_comments ON tbl_posts.id = tbl_comments.post_id 
LEFT JOIN tbl_person ON tbl_comments.Person_id = tbl_person.id;

所以不要做

tbl_comments.Person_id = 3

您需要像这样加入tbl_comments和tbl_person表:

tbl_comments.Person_id = tbl_person.id