0

我得到了这样的桌子votes

"id"    "votedElm"  "voteType"  "voteProcessed" "country"
"1"         "4" "0" "0" "US"
"2"         "5" "0" "0" "US"
"3"         "6" "1" "0" "US"
"4"         "8" "0" "0" "US"
"5"         "9" "0" "0" "US"
"6"         "10"    "0" "0" "US"
"7"         "10"    "0" "0" "US"
"8"         "10"    "0" "0" "US"
"9"         "8" "1" "0" "US"
"10"    "9" "1" "0" "US"
"11"    "20"    "1" "0" "US"
"12"    "10"    "1" "0" "US"
"13"    "10"    "1" "0" "US"
"14"    "20"    "0" "0" "US"
"15"    "22"    "0" "0" "US"
"16"    "20"    "0" "0" "US"
"17"    "21"    "0" "0" "US"
"18"    "10"    "0" "0" "US"
"19"    "10"    "0" "0" "US"
"20"    "20"    "0" "0" "US"
"21"    "21"    "0" "0" "US"
"22"    "22"    "0" "0" "US"
"23"    "22"    "0" "0" "US"
"24"    "22"    "1" "0" "US"

我使用这个 sql 来获得不同的喜欢并从中求和: select votedElm, count(votedElm) from votes where country = 'US' and voteType = 0 group by votedElm;

但是,在那张桌子上,我有voteType 0 and 1. 0是一+票,1是一-票。

在同一个sql中可以+加票,-减票吗?而不是为此有2个不同的查询?

我可以这样做吗?

4

4 回答 4

1

的,像这样:

SELECT
  votedElm,
  SUM(CASE WHEN voteType = 0 THEN 1 ELSE -1 END) AS Totalcount 
FROM votes 
WHERE country = 'US'
GROUP BY votedElm;

在这里查看它的实际效果:

于 2013-05-09T07:26:26.220 回答
1
SELECT votedElm, count(votedElm), 
    SUM(IF(voteType = 0, 1, -1)) AS totalVotes
FROM votes 
WHERE country = 'US' and voteType = 0 
GROUP BY votedElm;
于 2013-05-09T07:28:21.377 回答
0

您可以尝试以下解决方案

SELECT
  votedElm,
  SUM(CASE WHEN voteType = 0 THEN 1 ELSE -1 END) AS Totalcount 
FROM votes 
WHERE country = 'US'
GROUP BY votedElm;
于 2013-05-09T08:00:20.253 回答
0

试试喜欢

SELECT votedElm,SUM(CASE WHEN voteType = '0' THEN '1' ELSE '-1' END) AS count 
FROM `votes` 
WHERE country = 'US' and voteType = '0' 
GROUP BY votedElm;

或者你可以试试

$sql1 = "SELECT SUM(votedElm) AS count 
FROM `votes` 
WHERE country = 'US' and voteType = '0' 
GROUP BY votedElm";
$res1 = my_sql_query($sql1);

$sql2 = "SELECT SUM(votedElm) AS count 
FROM `votes` 
WHERE country = 'US' and voteType = '1' 
GROUP BY votedElm";
$res2 = my_sql_query($sql2);

然后

$res = $res1[0]['count'] - $res2[0]['count'];
于 2013-05-09T07:30:58.777 回答