嗨,我的查询组合记录时遇到问题。
我有两个表作者和出版物,他们通过出版物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时,它确实提供了所需的输出。 我无法弄明白,有谁知道我哪里出错了?
答案 0 :(得分:0)
要消除重复的作者,请更改:
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
答案 1 :(得分:0)
我想我不确定你为什么首先需要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")