UPDATE posts SET like_count = coalesce(cnt,0)
FROM (
SELECT post_id, count(*) cnt
FROM post_actions
WHERE post_action_type_id = 2 AND deleted_at IS NULL
GROUP BY post_id
) x
WHERE posts.like_count <> x.cnt AND posts.id = x.post_id
UPDATE topics SET like_count = coalesce(cnt,0)
FROM (
SELECT topic_id, sum(like_count) cnt
FROM posts
WHERE deleted_at IS NULL
GROUP BY topic_id
) x
WHERE topics.like_count <> x.cnt AND topics.id = x.topic_id
UPDATE user_stats SET likes_given = coalesce(cnt,0)
FROM (
SELECT user_id, count(*) cnt
FROM post_actions
WHERE post_action_type_id = 2 AND deleted_at IS NULL
GROUP BY user_id
) x
WHERE user_stats.likes_given <> x.cnt
AND user_stats.user_id = x.user_id
UPDATE user_stats SET likes_received = coalesce(cnt,0)
FROM (
SELECT posts.user_id, SUM(posts.like_count) cnt
FROM post_actions
LEFT JOIN posts ON post_actions.post_id = posts.id
WHERE post_action_type_id = 2 AND post_actions.deleted_at IS NULL
GROUP BY posts.user_id
) x
WHERE user_stats.likes_received <> x.cnt
AND user_stats.user_id = x.user_id