MySQL:在一个表中查找行而不在另一个表中查找行,找到

时间:2016-04-05 10:47:41

标签: mysql join

我正在努力探索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

对于我尝试解决的每个事件

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

我尝试了

的不同变体
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

1 个答案:

答案 0 :(得分:0)

您可以按照查询中提到的相同顺序使用以下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;