我有两张桌子:
Attendee(AttendeeId integer PRIMARY KEY, LastName, FirstName, etc...)
Company(CompanyId integer PRIMARY KEY, CompanyName, etc ...)
和他们之间的多对多关系:
CompanyAttendeeRelation
(
CompanyId integer REFERENCES Company (CompanyId),
AttendeeId integer REFERENCES Attendee (AttendeeId),
PRIMARY KEY (CompanyId, AttendeeId)
);
因此,从上面看,一家公司可以有一个以上的与会者,一个与会者可以在一个以上的公司。
但是,我试过了,例如:
SELECT (LastName || " " || FirstName) as AttendeeName,
CompanyAttendeeRelation.AttendeeId,
CompanyAttendeeRelation.CompanyId
FROM Attendee join CompanyAttendeeRelation on CompanyAttendeeRelation.AttendeeId = Attendee.AttendeeId join Company on CompanyAttendeeRelation.CompanyId = Company.CompanyId
GROUP BY LastName;
但我并没有让所有公司参加。也就是说,例如,有AttendeeId = 15
的与会者有CompanyId = 20
的公司和CompanyId = 100
的公司,我希望得到:
Doe John|15|20
Doe John|15|100
但我只是得到了:
Doe John|15|100
所以我不确定它是第一次匹配时停止的JOIN
,第二次永远不会被计算出来,或者某个重复的地方(在这种情况下为AttendeeId)被忽略了。
有什么想法吗?
答案 0 :(得分:2)
如果您想要所有组合,为什么要GROUP BY
?不用试试吧。
SELECT (LastName || " " || FirstName) as AttendeeName,
CompanyAttendeeRelation.AttendeeId,
CompanyAttendeeRelation.CompanyId
FROM Attendee
JOIN CompanyAttendeeRelation ON CompanyAttendeeRelation.AttendeeId = Attendee.AttendeeId
JOIN Company on CompanyAttendeeRelation.CompanyId = Company.CompanyId;
-- GROUP BY LastName;
更好的是,对于此特定查询,您根本不需要加入Company
。所以试试这个:
SELECT (LastName || " " || FirstName) as AttendeeName,
CompanyAttendeeRelation.AttendeeId,
CompanyAttendeeRelation.CompanyId
FROM Attendee
JOIN CompanyAttendeeRelation ON CompanyAttendeeRelation.AttendeeId = Attendee.AttendeeId;