我为自己加入一张桌子获得了一些很大的帮助,我正试图将它提升到一个新的水平。下面的SQL来自帮助,但我添加了以COUNT开头的选择行,到收件人表的内部联接以及分组依据。
SELECT
Event.EventID AS EventID,
Event.EventDate AS EventDateUTC,
Participant2.ParticipantID AS AwayID,
Participant1.ParticipantID AS HostID,
COUNT(Recipient.ChallengeID) AS AllChallenges
FROM Event
INNER JOIN Matchup Matchup1
ON (Event.EventID = Matchup1.EventID)
INNER JOIN Matchup Matchup2
ON (Event.EventID = Matchup2.EventID)
INNER JOIN Participant Participant1
ON (Matchup1.Host = 1
AND Matchup1.ParticipantID = Participant1.ParticipantID)
INNER JOIN Participant Participant2
ON (Matchup2.Host != 1
AND Matchup2.ParticipantID = Participant2.ParticipantID)
INNER JOIN Recipient
ON (Event.EventID = Recipient.EventID)
WHERE Event.CategoryID = 1
AND Event.Resolved = 0
AND Event.Type = 1
GROUP BY Recipient.ChallengeID
ORDER BY EventDateUTC ASC
我的目标是计算收件人表中与Event中的EventID匹配的行数。这段代码工作正常除了,我还希望得到收件人中有0个匹配行的结果。我想要15行(=事件数),但我得到2行,一行计数为1,一行计数为2(适用于内部联接,因为样本收件人表中有3行,一行一个EventID,两个用于另一个EventID)。
我认为LEFT join或OUTER join是我正在寻找的,但我知道我不太了解表是如何实际连接的。 LEFT join在那里给了我一行0,恰好是EventID 1(表中的第一件事),但这就是全部。错误告诉我,我不能只将INNER连接更改为OUTER。我尝试了一些括号和一些子选择等,但似乎无法使它工作。
答案 0 :(得分:1)
使用:
SELECT e.eventid,
e.eventdate AS EventDateUTC,
p2.participantid AS AwayID,
p1.participantid AS HostID,
COUNT(r.challengeid) AS AllChallenges
FROM EVENT e
JOIN Matchup m1 ON m1.eventid = e.eventid
AND m1.host = 1
JOIN Matchup m2 ON m2.eventid = e.eventid
AND m2.host != 1
JOIN Participant p1 ON p1.participantid = m1.participantid
JOIN Participant p2 ON p2.participantid = m2.participantid
LEFT JOIN RECIPIENT r ON r.eventid = e.eventid
WHERE e.categoryid = 1
AND e.resolved = 0
AND e.type = 1
GROUP BY e.eventid, e.eventdate, p2.participantid, p1.participantid
ORDER BY e.eventdate