I'm trying to return a sqlite3 query that will allow me to loop through social media posts and display the post and user details and the number of comments on each post.
I can't figure out how to write a sql query that gets the number of comments for the post.
Here is my database scheme in ERD:
And here is my query:
SELECT u.name, u.icon, p.date, p.title, p.message,
(SELECT comment.postId, COUNT(comment.Id)
FROM comment
WHERE comment.postID = p.Id) as commentno
FROM Post p, User u
WHERE p.userID = u.Id
What I see when I try to run this:
Error: sub-select returns 2 columns - expected 1
What I want to see:
Michael Scott, Michael.png, 2019-08-27, "Blog title", "Blog message", 7
See my comment above. I think you intended this:
SELECT u.name, u.icon, p.date, p.title, p.message,
c.postId, COUNT(c.Id) as commentno
FROM Post p LEFT JOIN User u ON p.userID = u.Id
LEFT JOIN Comment c on p.ID = c.PostID
GROUP BY u.name, u.icon, p.date, p.title, p.message, c.postId
UPDATE As was pointed out, my original answer had the same error (because I just quickly moved the alias. Here I reformatted your query to use JOINs
. I assumed that your Post
table has a comment ID, but you can figure out the appropriate columns for your JOIN
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.