如何将两个COUNT()语句组合成一个并获得差异?

时间:2011-01-26 18:57:24

标签: mysql

如何将以下两个查询合并为一个以获得result作为两个计数的差异。或结果如下:

result = vote1 - vote2

SELECT COUNT(id) AS vote1 FROM votes WHERE votes.voteTypeId = @voteType1 AND votes.userId = @userId
SELECT COUNT(id) AS vote2 FROM votes WHERE votes.voteTypeId = @voteType2 AND votes.userId = @userId

2 个答案:

答案 0 :(得分:3)

SELECT  SUM(votetypeid = @votetype1) - SUM(votetypeid = @votetype2)
FROM    votes
WHERE   userid = @userid
        AND votetypeid IN (@votetype1, @votetype2)

答案 1 :(得分:1)

select sum(case when voteTypeId = @voteType1 then 1
                when voteTypeId = @voteType2 then -1
                else 0
           end) as result
    from votes
    where userId = @userId