2016-05-13 73 views
1

我在我的数据库中的三个表从三个表获取数据的mysql加入

1.Users(ID,用户名)

2.Stories(ID,USER_ID,内容)这里是user_id关键forigen指Usersid

3.Comments(ID,USER_ID,story_id,评论)这里user_id是forigen键指Usersidstory_id是forigen键指Storiesid

我需要从Stories表中获取的故事名单与上storie笔者

下面的那个帖子和用户名评论总数是我对于

SELECT stories.id,stories.content,COUNT(stories.id) as totalcomment 
FROM stories 
JOIN comments 
ON stories.id=comments.story_id GROUP BY stories.id 

我会得到总查询

+0

什么阻止你加入'用户'表? –

+0

如何做到这一点? –

+0

同样的方式,你已经加入了评论 –

回答

0

的每个岗位的评论,但不能取storie作者(从用户表即用户名)的用户名试试这个:

SELECT stories.id,stories.content,COUNT(stories.id) as totalcomment, Users.username 
FROM stories, Users, comments 
WHERE stories.id=comments.story_id 
AND stories.user_id = Users.id 
GROUP BY stories.id 

或者与加盟:

SELECT stories.id,stories.content,COUNT(stories.id) as totalcomment, Users.username 
FROM stories 
JOIN comments ON stories.id=comments.story_id 
JOIN users ON stories.user_id = Users.id 
GROUP BY stories.id 

希望这个作品。

+0

我会得到未知列的错误消息,但是列存在\ –

+0

这将返回一个不确定的结果。 – Strawberry

1
SELECT s.id,s.content,COUNT(c.story_id) as totalcomment, u.username 
FROM stories s LEFT JOIN comments c ON (s.id=c.story_id) 
LEFT JOIN users u ON (s.user_id = u.id) 
GROUP BY s.id