poll_opts
表用于存储选项,poll_voted
表用于存储投票结果,pid代表poll id(unique),oid代表option id(unique for individual poll only)
poll_voted
[主键:pid.oid.emp]
+-----+-----+-------+
| pid | oid | emp |
+-----+-----+-------+
poll_opts
[主键:pid.oid]
+-----+-----+---------+
| pid | oid | opt |
+-----+-----+---------+
pid & oid 类型:int
, opt
类型:text
最佳答案
如果您还需要“不存在”的结果,则需要 left outer join
保留来自 poll_opts
的所有结果即使 poll_votes
中没有匹配项被发现。
查询:
select opt, count(vo.oid)
from poll_opts po
left outer join poll_voted vo on vo.oid = po.oid and po.pid=vo.pid
where po.pid = 3 -- 3
group by opt
输出:
opt count(vo.oid)
Chrome 0
Firefox 0
IE 0
MS Edge 0
Opera 1
测试数据:
CREATE TABLE poll_voted (`pid` int, `oid` int, `emp` int);
INSERT INTO poll_voted (`pid`, `oid`, `emp`)
VALUES
(1, 0, 1989),
(1, 2, 1989),
(1, 4, 1989),
(1, 6, 1989),
(3, 2, 1989)
;
CREATE TABLE poll_opts (`pid` int, `oid` int, `opt` varchar(15));
INSERT INTO poll_opts (`pid`, `oid`, `opt`)
VALUES
(1, 0, 'WinXP'),
(1, 2, 'wIN7'),
(1, 4, 'wIN 10'),
(1, 6, 'Ubuntu'),
(3, 0, 'IE'),
(3, 1, 'MS Edge'),
(3, 2, 'Opera'),
(3, 3, 'Chrome'),
(3, 4, 'Firefox')
;
关于mysql - 使用 Group By 连接 2 个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48609222/