SQL-Gruppierung mit mehreren Verknüpfungen Ergebnisse falsch kombiniert
-
23-09-2019 - |
Frage
Hallo, ich habe Probleme mit meiner Abfrage Datensätze kombiniert, wenn es nicht sollte.
Ich habe zwei Tabellen Autoren und Publikationen, werden sie durch Veröffentlichung ID in einer viele zu viele Beziehung zusammen. Wie jeder Autor kann viele Publikationen haben und jede Veröffentlichung viele Autoren hat. Ich möchte meine Abfrage jede Publikation für eine Reihe von Autoren zurück und schließen die ID von jedem der anderen Autoren, die zur Veröffentlichung in einem Feld gruppiert beigetragen haben. (Ich arbeite mit mySQL)
Ich habe versucht, es Bild grafisch unter
Table: authors Table:publications
AuthorID | PublicationID PublicationID | PublicationName
1 | 123 123 | A
1 | 456 456 | B
2 | 123 789 | C
2 | 789
3 | 123
3 | 456
Ich möchte meine Ergebnismenge die folgende
sein AuthorID | PublicationID | PublicationName | AllAuthors
1 | 123 | A | 1,2,3
1 | 456 | B | 1,3
2 | 123 | A | 1,2,3
2 | 789 | C | 2
3 | 123 | A | 1,2,3
3 | 456 | B | 1,3
Das ist meine Abfrage
Select Author1.AuthorID,
Publications.PublicationID,
Publications.PubName,
GROUP_CONCAT(TRIM(Author2.AuthorID)ORDER BY Author2.AuthorID ASC)AS 'AuthorsAll'
FROM Authors AS Author1
LEFT JOIN Authors AS Author2
ON Author1.PublicationID = Author2.PublicationID
INNER JOIN Publications
ON Author1.PublicationID = Publications.PublicationID
WHERE Author1.AuthorID ="1" OR Author1.AuthorID ="2" OR Author1.AuthorID ="3"
GROUP BY Author2.PublicationID
Aber es gibt die folgenden statt
AuthorID | PublicationID | PublicationName | AllAuthors
1 | 123 | A | 1,1,1,2,2,2,3,3,3
1 | 456 | B | 1,1,3,3
2 | 789 | C | 2
Es macht den gewünschten Ausgang liefern, wenn es nur einen AuhorID in der where-Anweisung ist. Ich habe es nicht aus der Lage, auf Figur Wer weiß, wohin ich gehe falsch?
Lösung
Zur Beseitigung doppelte Autoren ändern:
ON Author1.PublicationID = Author2.PublicationID
zu:
ON Author1.PublicationID = Author2.PublicationID AND
Author1.AuthorID <> Author2.AuthorID
Auch ändern:
GROUP BY Author2.PublicationID
zu:
GROUP BY Author1.AuthorID, Author2.PublicationID
Andere Tipps
Ich nehme an ich bin mir nicht sicher, warum Sie die GROUP BY müssen an erster Stelle. Warum können Sie verwenden eine korrelierte Unterabfrage in etwa so:
Select Author1.AuthorID
, Publications.PublicationID
, Publications.PubName
, (
Select GROUP_CONCAT(TRIM(Author2.AuthorID) ORDER BY Author2.AuthorID ASC)
From Authors As Author2
Where Author2.PublicationID = Publications.PublicationID
) AS 'AuthorsAll'
FROM Authors AS Author1
INNER JOIN Publications
ON Author1.PublicationID = Publications.PublicationID
Where Author1.AuthorId In("1","2","3")