PostgreSQL
 sql >> Base de Dados >  >> RDS >> PostgreSQL

Obter todas as postagens com soma de votos e se o usuário atual votou em cada postagem


Você está quase lá com sua consulta. Basta usar filter cláusula para obter a contagem de votos do usuário atual
SELECT 
    post.postID as postID, 
    post.title as title, 
    post.author as author,
    post.created as created,
    COALESCE(sum(votes.vote), 0) as voteCount, 
    COALESCE(sum(votes.vote) filter (where votes.username= 'username'), 0) as userVote  -- in '' just provide username for current login user
FROM post 
LEFT JOIN votes ON post.postID = votes.postID 
GROUP BY 1,2,3,4 
ORDER BY 5 DESC

Outra maneira é usar mais uma junção esquerda como abaixo:
SELECT 
    p.postID as postID, 
    p.title as title, 
    p.author as author,
    p.created as created,
    COALESCE(sum(v1.vote), 0) as voteCount, 
    COALESCE(v2.vote , 0) as userVote  -- in '' just provide username for current login user
FROM post p
LEFT JOIN votes v1 ON p.postID = v1.postID 
LEFT JOIN votes v2 on p.postID = v2.postID and v2.username='username'
GROUP BY 1,2,3,4,v2.vote
ORDER BY 5 DESC

DEMO