1

我有一个表格,包含以下列: id name vote

每个名字都是唯一的,每个投票要么是空的,要么包含一个名字。

我需要一个 MySQL 语句来返回每个人有多少票,以及谁为每个人投票。

我已经为此工作了 3 个小时,我完全不知所措,所以老实说,我不在乎它的效率有多低,或者你是如何做到的。

4

5 回答 5

3

SELECT name, count(*) as num_votes, GROUP_CONCAT(vote) as voted_by FROM table GROUP BY 1

于 2011-12-09T22:25:53.013 回答
2

多少票:

select 
 count(*) as numVotes, 
 vote
from
 voteTable
where
 vote IS NOT NULL
group by 
 vote
order by
 numVotes desc

谁为每个投票:

Select
 name,
 vote
from
 voteTable

...除非我误读了某些内容,否则应该就这么简单

于 2011-12-09T22:26:16.257 回答
2
select count(name), id from your_table where vote is not null group by (name) 
于 2011-12-09T22:27:31.167 回答
1

要获得每人的票数:

select vote, 
       count(*) as nbr_of_votes 
  from table 
 where vote is not null 
 group by vote 
 order by nbr_of_votes desc;

要让谁投票给谁,您基本上必须选择整个表格,省略空值

select vote, 
       name 
  from table
 where vote is not null 
 order by vote;
于 2011-12-09T22:27:41.683 回答
0
SELECT VOTE, COUNT(1) Number_Of_Votes,
GROUP_CONCAT(Name)
WHERE VOTE is Not NULL
GROUP BY VOTE
于 2011-12-09T22:32:35.983 回答