[英]joining the count of multiple tables
am building a blog for music and i want to count the number of likes and comments each blog post has when listing all the blog post. 我正在建立一个音乐博客,我想在列出所有博客帖子时计算每个博客帖子的喜欢和评论数。 i have the tables needed .
我有需要的桌子。 this is my query
这是我的查询
SELECT tbl_music.id,
tbl_music.name,
tbl_music.img,
tbl_music.date,
tbl_music.post,
COUNT(*) AS comms,
COUNT(*) AS liky
FROM tbl_music
LEFT JOIN tbl_mlikes
ON tbl_music.id = tbl_mlikes.mid
LEFT JOIN tbl_mus_coms
ON tbl_music.id = tbl_mus_coms.mid
WHERE tbl_music.status = 'Publish'
GROUP BY tbl_music.id
ORDER BY tbl_music.id
DESC
what i noticed is that it multiplies the count of comments with the count of likes and supplies the answer as the count of likes ie (if a post has 4 comments and 1 like, my query will display 4 comments and 4 likes) this has been really frustrating 我注意到的是,它将评论数乘以“喜欢”数并提供答案作为“喜欢”数,即(如果帖子中有4条评论和1条“赞”,我的查询将显示4条评论和4个“赞”),这是真令人沮丧
The problem is you have two different dimensions, so the query is producing a Cartesian product for each music id. 问题是您有两个不同的维度,因此查询为每个音乐ID生成笛卡尔乘积。
The best solution is to aggregate before joining: 最好的解决方案是在加入之前进行汇总:
SELECT m.*, l.likes, c.comments
FROM tbl_music m LEFT JOIN
(SELECT mid, COUNT(*) as likes
FROM tbl_mlikes
GROUP BY mid
) l
ON m.id = l.mid LEFT JOIN
(SELECT mc.mid, COUNT(*) as comments
FROM tbl_mus_coms mc
GROUP BY mc.mid
) c
ON m.id = c.mid
WHERE m.status = 'Publish'
ORDER BY m.id DESC ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.