mysql - 使用 Group By 连接 2 个表

标签 mysql sql join group-by

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

table data

最佳答案

如果您还需要“不存在”的结果,则需要 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

测试数据:

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/

相关文章:

mysql - 使用 sum() 子查询连接三个表

php - 我如何使这个查询 sql 注入(inject)证明?

MySQL 搜索(按相关性排序)

PHP PDO : Could my PHP be cleaner/more efficient?

MYSQL LEFT JOIN 只返回连接表中的一行

mysql - Hibernate 多对多映射和查询

php - 如何使用 PHP 将上传的 swf 文件存储在 MySQL 数据库中?

sql - 如何使用多个查询选择最高价格

mysql - 我将如何返回 SQL 数学运算的结果?

mysql - 在单个查询中按值获取行数