您遇到的主要问题是您的表格未标准化。我强烈建议您修复当前的表结构。一个可能的新表结构是:
/* Table for unique voters */
CREATE TABLE voters (
id INT UNSIGNED NOT NULL PRIMARY KEY,
name VARCHAR(255) NOT NULL
) ENGINE=InnoDB;
/* Table for unique candidates */
CREATE TABLE candidates (
id INT UNSIGNED NOT NULL PRIMARY KEY,
name VARCHAR(255) NOT NULL
) ENGINE=InnoDB;
/* Many-to-many table storing votes by voters for candidates */
CREATE TABLE votes (
voter_id INT UNSIGNED NOT NULL,
candidate_id INT UNSIGNED NOT NULL,
PRIMARY KEY (voter_id, candidate_id),
CONSTRAINT FOREIGN KEY (voter_id) REFERENCES voters (id),
CONSTRAINT FOREIGN KEY (candidate_id) REFERENCES candidates (id)
) ENGINE=InnoDB;
/* Populate data */
INSERT INTO voters (name)
VALUES ('Voter 1'), ('Voter 2'), ('Voter 3'), ('Voter 4');
INSERT INTO candidates (name)
VALUES ('George'), ('Carl'), ('Anthony'), ('Tony'), ('Stark');
INSERT INTO votes (voter_id, candidate_id)
VALUES (1,1), (1,2), (1,3),
(2,2), (2,4), (2,5),
(3,3), (3,1), (3,4),
(4,3), (4,1), (4,5);
然后,您可以通过连接两个表轻松获得结果:
/* query showing all voters and the candidates they voted for */
SELECT voters.name, candidates.name
FROM votes
INNER JOIN voters on votes.voter_id = voters.id
INNER JOIN candidates ON votes.candidate_id = candidates.id;
/* Finally, a query showing votes per candidate */
SELECT candidates.name, COUNT(*) AS votes
FROM votes
INNER JOIN candidates ON votes.candidate_id = candidates.id
GROUP BY candidates.id;
请参阅带有演示的 SQL Fiddle
但是,如果您无法更改表的设计,则可以通过取消透视多列中的数据来获得结果。您可以使用 UNION ALL 将多列取消透视为行以获取计数:
select name, count(*) TotalVotes
from
(
select senator_1 name
from yt
union all
select senator_2 name
from yt
union all
select senator_3 name
from yt
) d
group by name
order by totalVotes desc;
请参阅带有演示的 SQL Fiddle