查询反应计数

时间:2019-11-10 08:37:29

标签: mysql

我有桌子:

用户

user_id
name

帖子

post_id
user_id
post
image_path

反应

reaction_id
post_id
reaction
user_id
  

反应的值为{1: 'like', 2: 'dislike'}

现在,我希望每个反应都获得具有相应计数的所有帖子。

所以最终结果将是:

{
post_id: 1,
post: "Hello World",
image_path: "public/upload_123.png",
likes: 23,
dislikes: 18,
my_reaction: 1
}

3 个答案:

答案 0 :(得分:1)

您可以通过使用LEFT联接(以防万一帖子没有反应)联接表,然后进行条件聚合来实现:

select p.post_id, p.post, p.image_path,
  sum(r.reaction = 1) likes,
  sum(r.reaction = 2) dislikes
from posts p left join reactions r
on r.post_id = p.post_id
group by p.post_id, p.post, p.image_path 

答案 1 :(得分:0)

只需运行此代码即可。

SELECT a.post_id, a.post,a.image_path,b.reaction,count(b.reaction) 
from posts a 
INNER join reactions b on a.post_id=b.post_id 
group by a.post_id, a.post,a.image_path,b.reaction

答案 2 :(得分:0)

我终于得到了查询。它如下:

SELECT `posts`.`posts_id`, `users`.`user_id`, `posts`.`post`, `posts`.`file_path`, `posts`.`created_at`, `users`.`fname`, `users`.`mname`, `users`.`lname`, `r1`.`reaction`, IF(SUBSTRING_INDEX(posts.file_path, '.', -1) IN ('jpeg', 'jpg', 'png'), 'image', 'document') AS file_type, 
SUM(reactions.reaction = 1) AS likes, 
SUM(reactions.reaction = 2) AS hearts, 
SUM(reactions.reaction = 3) AS dislikes FROM `posts` 
LEFT JOIN `users` ON `posts`.`user_id` = `users`.`user_id` LEFT JOIN `reactions` ON `reactions`.`posts_id` = `posts`.`posts_id` 
LEFT JOIN `reactions` AS `r1` ON `r1`.`posts_id` = posts.posts_id AND r1.user_id = 1 WHERE `posts`.`deleted_at` IS NULL 
GROUP BY `posts`.`posts_id` 
ORDER BY `posts`.`created_at` DESC