制作mysql计数查询
经过4天的尝试和通过网络研究,我无法使我的愿望正常工作。
任何帮助将不胜感激!
在MySQL Workbench上执行
我得到了一个由3个表制成的数据库:
帖子 | 喜欢 | 用户 |
---|---|---|
名 | ID ID | ID |
ID | 标题 | userId(来自user.ID的外键) |
电子邮件 | 用户 | postid(来自posts.id的外键) |
密码 | 日期 | |
image image image | image image imageurl | |
userId(from user.id from user.id) |
我想要一个查询,可以从用户和帖子中获取详细信息,以及对于以ID的ID订购的每个帖子的总数,如果此ID不存在,则为0。 在这里,我要查询要做的事情的列表:
- 在用户和帖子中选择详细信息数据; (工作)
- 计算每个帖子的总计,如果任何帖子都不喜欢,总共给我0;
我的实际查询:
SELECT P.id, P.userId, P.title, P.content, P.date, P.imageUrl, U.username, U.permission, U.image,
COUNT(CASE WHEN L.postId = P.id THEN 1 ELSE NULL END) AS totalLikes
FROM posts AS P
LEFT JOIN user AS U
ON U.id = P.userId
LEFT JOIN likes AS L
ON P.id = L.postId
ORDER BY P.id DESC;
这仅返回1个帖子,其中包含数据库中所有喜欢的计数,因此不是我所期望的:-(
after 4 days of tries and researchs over the web I can't make my wishes working.
Any help would be appreciated !
Performed on MYSQL WORKBENCH
I got a DB made of 3 tables :
user | Posts | likes |
---|---|---|
username | id | id |
id | title | userId (foreign key from user.id) |
content | postId (foreign key from posts.id) | |
password | date | |
image | imageUrl | |
userId (foreign key from user.id) |
I want a query that would take specifics datas from USER and POSTS plus a total count of likes for each post ordered by id of post and a total result of 0 if no likes exist with this id.
Here the list of what I want my query to do :
- Select specifics datas in USER and POSTS; ( working )
- COUNT the total of LIKES for each POSTS and give me a total of 0 if any post has no likes;
My Actual Query :
SELECT P.id, P.userId, P.title, P.content, P.date, P.imageUrl, U.username, U.permission, U.image,
COUNT(CASE WHEN L.postId = P.id THEN 1 ELSE NULL END) AS totalLikes
FROM posts AS P
LEFT JOIN user AS U
ON U.id = P.userId
LEFT JOIN likes AS L
ON P.id = L.postId
ORDER BY P.id DESC;
This is returning only 1 post with a count of all the likes in database so not what i'm expecting :-(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
仅在
中进行聚合,仅喜欢
,然后将其他表加入聚合的结果集:Do the aggregation inside
likes
only and then join the other tables to the resultset of the aggregation: