1

I have three tables in my database

1.Users (id,username)

2.Stories (id,user_id,content) here user_id is forigen key refers Users table id

3.Comments (id,user_id,story_id,comment) here user_id is forigen key refers Users table id and story_id is forigen key refers Stories table id

I need to get list of stories from Stories table with total number of comments on that post and username of the storie author

Here is my query for that

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

I will get the total comment of the each post ,but can't fetch the username of the storie author (ie username from Users table)

4
  • What is stopping you from joining Users table? Commented May 13, 2016 at 9:04
  • The same way, you've joined comments Commented May 13, 2016 at 9:05
  • Have you maintained relation of users table with comments or stories? Commented May 13, 2016 at 9:07
  • Yes i maintained with both tables Commented May 13, 2016 at 9:09

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

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

Or with join:

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

Hope this works.

2 Comments

I will get the error messages unknown column but ccolumn is present\
This will return an indeterminate result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.