Skip to content
Advertisement

Get all posts with sum of votes and if current user voted each post

If have the following two PostgreSQL tables:

Post table:

postid | title | author | created

Vote table:

postid | username | vote

where vote is equal to 1 if the user voted the post up, 0 if the user did not vote and -1 if the user voted the post down.

I want to receive now for every post its title, author, created date, sum of all votes and the vote of the current logged in user. I wrote a query to receive everything except the vote of the current user like this:

I tried to fetch the current userVote by running a subquery like

However it does not seem to work and I am unable to figure out why and how to fix it. Any help would be very appreciated 🙂

Advertisement

Answer

You are almost there with your query. Just use filter clause to get current user’s vote count

Another way is by using one more left join like below:

DEMO

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement