【问题标题】:MySQL: Find rows in one table and not the other, find bothMySQL:在一个表中查找行而不是另一个,同时查找
【发布时间】:2016-07-25 06:28:08
【问题描述】:

我很难理解 MySQL 连接。我有三张桌子

-- events
id  name
1   Event 1
2   Event 2

--  registrations
id   event  name
1    1      Alice
2    1      Bob
3    2      Alice
4    2      Charlie

-- scores
id  event  name     score
1   1      Alice    10
2   1      Charlie  20
3   2      Alice    15
4   2      Bob      30

对于我正在努力解决的每个事件

  • 有多少人注册(注册表中的行)但未获得分数(不包括分数表中的行)
  • 有多少人获得了分数(分数表中的行)但未注册(不包括注册表中的行)
  • 有多少人同时注册并获得分数

我尝试了不同的变体

SELECT  *
FROM    registrations r
LEFT JOIN scores s
ON      r.event = s.event
WHERE   s.event IS NULL
AND r.event = 1

但我不确定我应该加入什么:eventname 但两者都不是空的,而且我似乎从来没有得到我正在寻找的正确数字。最后的结果应该是这样的

      name     reg_only score_only reg&score total 
event Event 1  1        1          1         3

【问题讨论】:

  • 您是否尝试将表格添加到您的 * 语句中? "select r.* from registrations r....." 问题可能是事件列存在于几个涉及的表中。

标签: mysql join


【解决方案1】:

您可以按照您在查询中提到的顺序使用以下 3 个查询-

SELECT e.id, e.name, COUNT(r.id) AS registered_user
FROM `events` AS e
INNER JOIN registrations AS r ON e.id=r.event 
LEFT JOIN scores AS s ON e.id = s.event
WHERE   s.event IS NULL;

SELECT e.id, e.name, COUNT(r.id) AS scored_user
FROM `events`scores AS e
INNER JOIN scores AS s ON e.id=s.event 
LEFT JOIN registrations AS r ON e.id = r.event
WHERE   r.event IS NULL;

SELECT e.id, e.name, COUNT(*) AS both_user
FROM `events` AS e
INNER JOIN registrations AS r ON e.id=r.event 
INNER JOIN scores AS s ON e.id = s.event;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    相关资源
    最近更新 更多