嗨,我有我的查询麻烦时,它不应该结合记录。

我有两个表作者和出版物,它们被公开在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

它确实当仅存在一个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归因
不隶属于 StackOverflow
scroll top