编程语言
首页 > 编程语言> > php – 计算正面和负面投票的数量:

php – 计算正面和负面投票的数量:

作者:互联网


502 Bad Gateway
<body bgcolor="white">


502 Bad Gateway

解决方法:

您可以在一个查询中进行计数:

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

标签:php,mysql,voting
来源: https://codeday.me/bug/20190521/1148723.html