MYSQL:复杂查询问题
我正在处理民意调查:每个民意调查都有很多选项,用户可以在民意调查中投票一次。 因此,我有一个包含以下字段的“投票”表:
- id(投票的 id)
- option_id(所选民意调查选项的 id)
- user_id(用户的 id)
- poll_id(民意调查的 id)
所以这就是我正在尝试这样做:给定一个 poll_ids 数组,我希望有一个查询返回每次民意调查中得票最多的选项。 因此,如果我给出的 poll_id 为 1 & 2,我想取回民意调查 1 和 2 中得票最多的选项。 2.我已经尝试过以下操作:
SELECT
t1.poll_id,
t1.option_id,
count(t1.option_id) AS num_votes,
t2.option_id AS user_vote
FROM
votes AS t1
JOIN
votes AS t2
ON
t1.id = t2.id
WHERE
t1.poll_id IN (30,40)
GROUP BY
t1.option_id;
这几乎可以解决问题...但是为我提供了所有民意调查选项以及所提供的每个民意调查的相应投票,而不仅仅是得票最多的选项。 如果有人有任何想法,我将非常感激。 谢谢。
I am working with polls: Each poll has many options and users can vote in polls once. Thus I have a 'votes' table with the following fields:
- id (id of the vote)
- option_id (id of the poll option chosen)
- user_id (id of the user)
- poll_id (id of the poll)
So here is what I'm trying to do: Given an array of poll_ids, I want to have a query return the most voted on option for each poll. Thus if I give poll_id's of 1 & 2, I want to get back the most voted on options for polls 1 & 2. I have tried the following:
SELECT
t1.poll_id,
t1.option_id,
count(t1.option_id) AS num_votes,
t2.option_id AS user_vote
FROM
votes AS t1
JOIN
votes AS t2
ON
t1.id = t2.id
WHERE
t1.poll_id IN (30,40)
GROUP BY
t1.option_id;
That almost does the trick...but gives me all poll options with corresponding votes for each poll provided, not just the most voted option. If anyone has any ideas, I'd really appreciate it. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为你不需要自连接来解决这个问题,但夸斯诺伊的答案似乎是正确的。
I don't think you'll need a self join to solve this, but Quassnoi's answer seems correct.
夸斯诺伊的回答就可以了。 您不需要连接表,只需使用 count(*) 操作返回总和,然后按该总和排序以查看谁做得最好。 GROUP BY 告诉 mysql 引擎要计算哪些类别,在您的情况下计算不同的轮询选项。
Quassnoi's answer will do it. You don't need to join the table you just need to use a count(*) operation to return the sum and then order by that sum to see who does best. The GROUP BY tells the mysql engine what categories to count, in your case to count the different poll options.
这样的事情会做吗?
Will something like this do?