1

I'm trying to get all likes/dislikes of multiple post. The problem can be summarized as:

  • posts table: id, content, user_id (fk)
  • users table: id, name
  • likes table: post_id (fk), user_id (fk), is_liked, is_disliked

To fit my use case, I need to get the list of all likes/dislikes so I've first tried this:

SELECT 
 posts.id, posts.content, users.name as author
 ARRAY(SELECT user_id FROM likes WHERE is_liked and post_id = posts.id) as likes,
 ARRAY(SELECT user_id FROM likes WHERE is_disliked and post_id = posts.id) as dislikes
FROM 
 posts
 INNER JOIN users ON posts.user_id = users.id

This is clearly not optimized. That's why I've tried something with another join on likes table and the array_agg function but I can't figure out how to get two different arrays for likes and dislikes.

Laurenz Albe
62.1k4 gold badges57 silver badges93 bronze badges
asked Mar 3, 2020 at 13:20

1 Answer 1

2

That should be simple with array_agg and additional FILTER clauses:

SELECT 
 posts.id, posts.content, users.name as author
 array_agg(likes.user_id) FILTER (WHERE likes.is_liked) as likes,
 array_agg(likes.user_id) FILTER (WHERE likes.is_disliked) as dislikes
FROM posts
 INNER JOIN users ON posts.user_id = users.id
 INNER JOIN likes ON likes.post_id = posts.id
GROUP BY posts.id, posts.content, users.name;
answered Mar 3, 2020 at 13:34
2
  • Available since Postgres 9.4, not enough people know about the filter clause. Commented Mar 3, 2020 at 13:52
  • Indeed, I wasn't aware of it, thank you very much! Commented Mar 3, 2020 at 14:05

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.