mysql查询三重加入+三重计数
我需要执行查询,但不能使其可行... 任何帮助将不胜感激!
在MySQL Workbench上执行
得到了一个由4个表制成的数据库:
用户 | 帖子 | 喜欢 | 注释 |
---|---|---|---|
用户 | 名ID ID | ID | ID |
ID | 标题 | userId(来自用户。ID的外键) | 内容 |
电子邮件email | 我 | postid(来自posts.id from posts.id) | 日期 |
密码 | 日期日期 | userid(from user键。 ID) | |
Image | ImageUrl | PostID(来自posts.id的外键) | |
Bio | UserID(user.id的外键) | ||
创建的 |
我想要一个查询,可以从用户中获取特定数据,以及特定用户的总数,帖子和评论的总数,如果该用户中不存在LIKE /帖子 /注释,则总数为0。 我基本上需要用户的统计数据。
目前,我的查询为我提供了用户名 /允许 / image / bio和创建< / em>的良好信息,但所有计数< / strong>返回我 0。
SELECT u.username, u.permission, u.image, u.bio, u.createDate,
COALESCE(P.totalPosts, 0) AS totalPosts,
COALESCE(C.totalComms, 0) AS totalComms,
COALESCE(L.totalLikes, 0) AS totalLikes
FROM user AS u
LEFT JOIN(
SELECT userId, COUNT(*) AS totalPosts
FROM posts
) AS P ON P.userId = u.id
LEFT JOIN(
SELECT userId, COUNT(*) AS totalComms
FROM comments
) AS C ON C.userId = u.id
LEFT JOIN(
SELECT userId, COUNT(*) AS totalLikes
FROM likes
) AS L ON L.userId = u.id
WHERE u.username = 'Alfred';
感谢您的时间&lt; 3!
I need to perform a query but can't make it works...
Any help would be appreciated !
Performed on MYSQL WORKBENCH
I got a DB made of 4 tables :
user | Posts | likes | comments |
---|---|---|---|
username | id | id | id |
id | title | userId (foreign key from user.id) | content |
content | postId (foreign key from posts.id) | date | |
password | date | userId (foreign key from user.id) | |
image | imageUrl | postId (foreign key from posts.id) | |
bio | userId (foreign key from user.id) | ||
createDate |
I want a query that would take specifics datas from USER plus a total count of likes, posts and comments for a specific user and a total result of 0 if no likes / posts / comments exist within this user.
I basically need stats for my user.
My query at the moment give me the good infos for username / permission / image / bio and createDate but return me 0 for all counts.
SELECT u.username, u.permission, u.image, u.bio, u.createDate,
COALESCE(P.totalPosts, 0) AS totalPosts,
COALESCE(C.totalComms, 0) AS totalComms,
COALESCE(L.totalLikes, 0) AS totalLikes
FROM user AS u
LEFT JOIN(
SELECT userId, COUNT(*) AS totalPosts
FROM posts
) AS P ON P.userId = u.id
LEFT JOIN(
SELECT userId, COUNT(*) AS totalComms
FROM comments
) AS C ON C.userId = u.id
LEFT JOIN(
SELECT userId, COUNT(*) AS totalLikes
FROM likes
) AS L ON L.userId = u.id
WHERE u.username = 'Alfred';
Thanks for your time <3 !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您所缺少的是:
在所有子征服中:
但是,所有这些子征服都为所有用户汇总,而不仅对您想要结果的特定用户,这对性能不利。
如果您使用过的话会更好相关子征服:
What you are missing is:
in all your subqueries:
But, all these subqueries do aggregation for all users and not only for the specific user that you want the results and this is bad for performance.
It would be better if you used correlated subqueries: