您可以在一个查询中进行计数:
Select Sum( Case When value < 0 Then 1 Else 0 End ) As NegVotes
, Sum( Case When value > 0 Then 1 Else 0 End ) As PosVotes
From author_vote
Where post_id = ...
如果你想要每个帖子的正面和负面投票:
Select post_id
, Sum( Case When value < 0 Then 1 Else 0 End ) As NegVotes
, Sum( Case When value > 0 Then 1 Else 0 End ) As PosVotes
From author_vote
Group By post_id
如果您想要合并第一个查询和第二个查询,您可以获得:
Select post....
, author.username
, Coalesce(post_count.NegVotes,0) As NegVotes
, Coalesce(post_count.PosVotes,0) As PosVotes
From post
Join author
On author.id = post.author_id
Left Join (
Select post_id
, Sum( Case When value < 0 Then 1 Else 0 End ) As NegVotes
, Sum( Case When value > 0 Then 1 Else 0 End ) As PosVotes
From author_vote
Group By post_id
) As post_count
On post_count.post_id = post.post_id