这是一个没有问题的MySql 5.0.51执行的查询:
SELECT cc_split.idSplit,
count( voteup.vote),
count( votedown.vote)
FROM cc_split
LEFT JOIN cc_split_usager AS voteup ON voteup.idSplit = cc_split.idSplit
AND voteup.vote >0
LEFT JOIN cc_split_usager AS votedown ON votedown.idSplit = cc_split.idSplit
AND votedown.vote <0
WHERE cc_split.isArchived = false
GROUP BY cc_split.idSplit
LIMIT 0, 30
问题在于COUNT没有显示我想要的内容。您是否可以看到,它需要cc_ split_ usager并且应该计算正数的投票数量,另一方面计算负数的投票数量。上面的代码显示数字2 upvote和2 downvote实际上它应该是2 upvote和1 downvote。在单个SQL查询中有什么技巧可以使用upvote和downvote的数量。
表格如下:
cc_split:
-idSplit
-...
cc_split_usager:
-idSplit
-vote (can be +1 or -1)
-...
对我有任何暗示吗?
答案 0 :(得分:1)
尝试:
SELECT s.idSplit,
count(case when v.vote > 0 then 1 else null end) as VoteUp,
count(case when v.vote < 0 then 1 else null end) as VoteDown
FROM cc_split s
LEFT JOIN cc_split_usager AS v ON v.idSplit = s.idSplit
WHERE s.isArchived = false
GROUP BY s.idSplit
LIMIT 0, 30
答案 1 :(得分:1)
试试这个:
SELECT s.idSplit,
Sum( Case When vote > 0 Then 1 Else 0 End) UpVotes,
Sum( Case When vote < 0 Then 1 Else 0 End) DownVotes
FROM cc_split s
LEFT JOIN cc_split_usager v
ON v.idSplit = s.idSplit
WHERE s.isArchived = false
GROUP BY s.idSplit
LIMIT 0 , 30