1

我有一个将值写入 mysql 数据库表的投票应用程序。这是一个偏好/加权投票系统,因此人们选择第一个选项、第二个选项和第三个选项。这些都进入表中的单独字段。我正在寻找一种编写查询的方法,该查询将为响应分配数值(第一个响应为 3,第二个响应为 2,第一个响应为 1),然后显示带有总分的值。我已经能够为总票数做到这一点

select count(name) as votes,name 
from (select 1st_option as name from votes 
      union all 
      select 2nd_option from votes 
      union all 
      select 3rd_option from votes) as tbl 
group by name 
having count(name) > 0 
order by 1 desc;

但还没有完全弄清楚如何为每一列中的响应分配值,然后将它们拉到一起。任何帮助深表感谢。谢谢!

4

1 回答 1

3

你可以这样做:

select sum(score) as votes,name 
from (select 1st_option as name, 3 as score from votes 
      union all 
      select 2nd_option as name, 2 as score from votes 
      union all 
      select 3rd_option as name, 1 as score from votes) as tbl 
group by name;
于 2013-01-08T14:55:31.713 回答