使用Group By连接2个表

时间:2018-02-04 14:38:03

标签: mysql sql join group-by

用于存储选项的

poll_opts表和用于存储投票结果的poll_voted,pid代表投票ID(唯一),oid代表选项id(仅用于个人投票的唯一)

poll_voted [主键:pid.oid.emp]

+-----+-----+-------+
| pid | oid | emp   |
+-----+-----+-------+

poll_opts [主键:pid.oid]

+-----+-----+---------+
| pid | oid | opt     |
+-----+-----+---------+
pid& oid类型:intopt类型:text

table data

1 个答案:

答案 0 :(得分:1)

如果您需要"不存在"即使找不到left outer join中的匹配项,您也需要poll_opts保留poll_votes的所有结果。

MySql 5.7 Join Syntax

查询:

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

TESTDATA:

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')
;