【问题标题】:Joining 2 tables with Group By使用 Group By 连接 2 个表
【发布时间】:2018-02-04 14:38:02
【问题描述】:

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

poll_voted[主键:pid.oid.emp]

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

poll_opts [主键:pid.oid]

+-----+-----+---------+
| pid | oid | opt     |
+-----+-----+---------+

pid & oid 类型:intopt 类型:text

【问题讨论】:

  • 不要在 where 子句中连接表,使用正确的连接语法。哪个键?用于将 poll_voted 与 poll_opts 关联起来
  • @PatrickArtner pid 可以使用。 pid 代表投票 id(唯一),oid 代表选项 id(仅对每个投票都是唯一的)
  • 您在寻找什么? Gordon Linoff 为您提供了一份声明。如果它有“错误”的输出,可能是你没有说你的预期输出是什么?您的 poll_voted 不包含 poll1 的任何 oid 的条目,因此在加入时,除非您使用某种对数据没有多大意义的左联接,否则不会全部计算在内。分组也没有多大意义,因为每个组只包含一个元素,所以分组对你没有任何作用......
  • @PatrickArtner 我已经添加了详细信息。希望这有助于解决问题。

标签: mysql sql join group-by


【解决方案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

测试数据:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-08
    • 2021-06-06
    • 2021-04-18
    相关资源
    最近更新 更多