我能够在民意调查中得到总票数。但我需要得到选民没有投票的总数。例如,选民#1仅投票给总统类别和参议员类别,选民#2仅投票给副主席和参议员。最后,选民#3没有投票,我仍然把选民投票#3投票,并将其留空。所以结果应该是 在特定类别中投票的数字选民。
PRESIDENT : 2
VICE PRESIDENT : 2
SENATORS : 1
在第1号选民没有投票支持vp的情况下,选民#2没有投票支持pres,选民#3则投了空票。
这是我的表格。
Polls
id | poll_title
1 | presidential election
Poll_categories
id | poll_id | category_name
1 | 1 | President
2 | 2 | Vice-President
3 | 3 | Senator
Poll_items
id | poll_category_id | item_name
1 | 1 | Obama
2 | 1 | Bush
3 | 1 | Clinton
4 | 2 | Biden
5 | 3 | Shelby
6 | 3 | Murkowski
Poll_votes
id | voters_id | poll_item_id
1 | 1 | 1
2 | 1 | 5
3 | 1 | 6
4 | 2 | 4
5 | 2 | 6
6 | 3 | NULL
到目前为止,这是我的查询,但我不知道接下来该做什么。我也无法显示elections_id 3,因为它是NULL
select c.id, c.category_name, v.voters_id from poll_category c
LEFT JOIN (select v.user_id, v.poll_item_id, i.poll_category_id as cat_id, i.item_name
from poll_votes v
LEFT JOIN poll_items i on i.id = v.poll_item_id) v
ON v.cat_id = c.id
WHERE c.poll_id = 1
答案 0 :(得分:1)
您可以使用以下查询:
SELECT pc.id, COUNT(*)
FROM Poll_categories AS pc
CROSS JOIN (
SELECT DISTINCT voters_id
FROM Poll_votes) AS voters
LEFT JOIN (
SELECT voters_id, poll_category_id
FROM Poll_votes AS pv
LEFT JOIN Poll_items AS pi ON pv.poll_item_id = pi.id
) AS voters_cat
ON pc.id = voters_cat.poll_category_id AND voters.voters_id = voters_cat.voters_id
WHERE voters_cat.poll_category_id IS NULL
GROUP BY id