用户的MySQL投票历史记录,每个项目的总投票数

时间:2015-09-29 17:30:40

标签: mysql sql join

我有类似这些的表:

names (these are being voted on)
+----+-------+
| ID | name  |
+----+-------+
|  1 | name1 |
|  2 | name2 |
|  3 | name3 |
|  4 | name4 | 
+----+-------+

votes
+----+----------+------+---------+
| ID | voter_id | time | name_id |
+----+----------+------+---------+
|  1 |     1    |   x  |    1    |
|  2 |     2    |   x  |    1    |
|  3 |     3    |   x  |    2    |
|  4 |     4    |   x  |    2    |
|  5 |     5    |   x  |    4    |
+----+----------+------+---------+

expected result for voter_id 1
| n.ID | n.name | v.time | votecount|
+------+--------+--------+----------+
|   1  |  name1 |   x    |      2   |
+------+--------+--------+----------+

我使用的查询:

SELECT COUNT(DISTINCT v.VOTE_ID) VOTECOUNT, v.VOTE_TIME, v.VOTER_ID, n.ID, n.NAME
FROM `votes` as v
LEFT JOIN `names` as n
ON n.ID = v.NAME_ID
WHERE v.VOTER_ID = :id
GROUP BY n.ID
ORDER BY v.TIME DESC

替代查询:

SELECT COUNT(DISTINCT v.VOTE_ID) VOTECOUNT, v.VOTE_TIME, v.VOTER_ID, n.ID, n.NAME
FROM `votes` as v
LEFT JOIN `names` as n
ON n.ID = v.NAME_ID
GROUP BY n.ID
HAVING v.VOTER_ID = :id
ORDER BY v.TIME DESC

我试图获取用户投票的项目列表,并计算每个项目的总票数。

如果我使用WHERE子句,则votecount显然总是1,但它会获得用户投票的所有项目。
我已经尝试使用HAVING voter_id来保持投票总数和那种作品,但是由于某些原因,用户投票的一些项目被省略了。改变RIGHT JOIN的LEFT JOIN将给出略有不同的列表,但永远不会完成。 会有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

两件事。

首先,尝试使用HAVING替换第二个查询中的HAVING MAX(CASE WHEN v.VOTER_ID = :id THEN 1 ELSE 0 END) = 1子句。

其次,您的选择列表与您的群组不匹配,所以我不确定您要在那里做什么。什么是时间列?我对你想要的东西的尝试看起来像是:

SELECT COUNT(DISTINCT v.VOTE_ID) VOTECOUNT, n.ID, n.NAME
FROM `votes` as v
LEFT JOIN `names` as n
ON n.ID = v.NAME_ID
GROUP BY n.ID, n.NAME
HAVING MAX(CASE WHEN v.VOTER_ID = :id THEN 1 ELSE 0 END) = 1