一个返回所有帖子的查询,以及查看的次数,以及帖子有多少喜欢。问题是它返回重复,因为我在查询中有另一个连接
SELECT count(bv.postId) as views, SUM(if(vote=1, 1, 0)) as likes, SUM(if(vote=-1, 1, 0)) as meeh, GROUP_CONCAT(taxonomy_id) as target, GROUP_CONCAT(t.name) as tname, `t`.`type` as `ttype`, `users`.`fullname`, `users`.`picture`, `users`.`role`, `users`.`picture`, `blog`.* FROM `blog`
INNER JOIN `blog_taxonomy` `bt` ON `bt`.`blog_id` = `blog`.`id`
INNER JOIN `users` ON `users`.`id` = `blog`.`user_id`
INNER JOIN `taxonomy` `t` ON `t`.`id` = bt.`taxonomy_id`
LEFT JOIN `blog_views` `bv` ON `blog`.`id` = `bv`.`postId`
WHERE MONTH(blog.time_posted) = 4 AND `blog`.`deleted` =0 GROUP BY `blog`.`id` ORDER BY `blog`.`id` DESC
blog_views表是一个简单的表格,用于跟踪谁看到了什么帖子,以及他是否喜欢
Table:blog_views
postId userId vote[int values, 1 for like, -1 for dislike and 0 default]
问题是视图的数量总是返回b * blog_taxonomy表的数量!我用来控制帖子上的标签。
Table blog_taxonomy:
taxonomy_id post_id
1 1
2 1
Table Taxonomy
id name
1 art
2 music
这是用于将帖子与标签链接的多对多表格。从查询中删除它解决问题:(但我需要它在那里!
我尝试在组中添加bv.postId,但似乎根本没有效果!
在正常情况下,我可以使用
获取我想要的帖子数据select count(bv.postId) as views, SUM(if(vote=1, 1, 0)) as likes, SUM(if(vote=-1, 1, 0)) as meet from blog_views where postId = ?{blog.id}
group by postId
我在这里缺少什么?
修改
使用子查询修复了问题。那么为什么子查询方法工作正常并且连接不起作用?
SELECT bv.views, bv.likes, bv.meeh, GROUP_CONCAT(taxonomy_id) as target, GROUP_CONCAT(t.name) as tname, `t`.`type` as `ttype`, `users`.`fullname`, `users`.`picture`, `users`.`role`, `users`.`picture`, `blog`.* FROM `blog`
INNER JOIN `blog_taxonomy` `bt` ON `bt`.`blog_id` = `blog`.`id`
INNER JOIN `users` ON `users`.`id` = `blog`.`user_id`
INNER JOIN `taxonomy` `t` ON `t`.`id` = bt.`taxonomy_id`
LEFT JOIN (select count(*) as views,postId,SUM(if(vote=1, 1, 0)) as likes, SUM(if(vote=-1, 1, 0)) as meeh from `blog_views` group by postId) `bv` ON `bt`.`blog_id` = `bv`.`postId`
WHERE MONTH(blog.time_posted) = 4 AND `blog`.`deleted` =0 GROUP BY `blog`.`id` ORDER BY `blog`.`id` DESC
答案 0 :(得分:0)
根据我的理解,您在分类表上的JOIN条件不正确
JOIN taxonomy t ON t.id = taxonomy_id
taxonomy_id
添加别名,即bt.taxonomy_id
,如果仍然无效