[英]How do I correctly write a sub-query to get count of comments for each post?
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. 我正在尝试返回一个sqlite3查询,该查询将允许我循环浏览社交媒体帖子并显示帖子和用户详细信息以及每个帖子的评论数。
I can't figure out how to write a sql query that gets the number of comments for the post. 我不知道如何编写一个SQL查询来获取帖子的评论数。
Here is my database scheme in ERD: 这是我在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 错误:子选择返回2列-预期为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
. UPDATE如前所述,我的原始答案有相同的错误(因为我只是快速移动了别名。在这里,我将查询重新格式化为使用JOINs
。我假设您的Post
表具有注释ID,但是您可以找出适当的列为您的JOIN
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.