我正在努力探索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
但是我不确定我应该加入什么:event
或name
但是两者都不为空,我似乎永远无法得到我正在寻找的正确数字。最后的结果应该是
name reg_only score_only reg&score total
event Event 1 1 1 1 3
答案 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;