[英]SQL Grouping with multiple joins combining results incorrectly
嗨,我在查询查询合并记录时遇到了麻烦。
我有两个表Authors和Publications,它们与Publication ID之间存在多对多关系。 因为每个作者可以有很多出版物,每个出版物也有很多作者。 我希望我的查询返回一组作者的每个出版物,并将对出版物有贡献的其他每个作者的ID归入一个字段。 (我正在使用mySQL)
我试图在下面以图形方式显示它
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
我希望我的结果集如下
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
这是我的查询
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
但是它返回以下内容
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
当where语句中只有一个AuhorID时,它将提供所需的输出。 我一直无法弄清楚,有人知道我要去哪里了吗?
要消除重复的作者,请更改:
ON Author1.PublicationID = Author2.PublicationID
至:
ON Author1.PublicationID = Author2.PublicationID AND
Author1.AuthorID <> Author2.AuthorID
另外,更改:
GROUP BY Author2.PublicationID
至:
GROUP BY Author1.AuthorID, Author2.PublicationID
我想我不确定您为什么首先需要GROUP BY。 您为什么不能像这样使用相关子查询:
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.