我的数据库中有三个表
1.Users(id,username)
2.Stories(id,user_id,content)here user_id
是forigen key引用Users
table id
3.评论(id,user_id,story_id,comment)这里user_id
是forigen key引用Users
table id
而story_id
是forigen key引用{{1} } table Stories
我需要从id
表中获取故事列表,其中包含该帖子的评论总数和storie作者的用户名
这是我对
的查询Stories
我会得到每篇帖子的总评论,但无法获取storie作者的用户名(即用户表中的用户名)
答案 0 :(得分: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
答案 1 :(得分:0)
试试这个:
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
希望这有效。