没有重复的多对多关系

时间:2013-08-11 21:06:57

标签: sql-server many-to-many group-concat

我正在尝试解决多对多关系的问题。

我有3张桌子:

Article
-------
ArticleID
FilePath
Title
Description

Author
--------
AuthorID
AuthorFName /* Father last name */
AuthorMName /* Mother last name */
AuthorName

ArticleAuthor
-------------
AuthorID
ArticleID
Foreign KEY (AuthorID) REFERENCES Author(AuthorID),
FOREIGN KEY (ArticleID) REFERENCES Article(ArticleID),
PRIMARY KEY (AuthorID, ArticleID)

作者表有2位作者:

ID FName MName Name
-- ----- ----- ----
1  XXX   YYY   AAA
2  MMM   NNN   BBB

文章:

ID FilePath    Title  Description (optional)
-- --------    -----  ----------------------
1  /path/file  '....' ''

和ArticleAuthor

ArticleID AuthorID
--------- --------
1         1
1         2

我现在使用的查询是:

SELECT DISTINCT ArticleAuthor.ArticleID,
    STUFF(
        (
            SELECT ',' + CONCAT(AuthorFName, ' ', AuthorMName, ' ', AuthorName)
            FROM FinderSchema.Author
            WHERE Author.AuthorID = ArticleAuthor.AuthorID
            FOR XML PATH(''), TYPE
        ).value('.', 'varchar(max)'), 1, 1, ''
    ) AS Authors
FROM FinderSchema.ArticleAuthor
    LEFT JOIN FinderSchema.Author ON ArticleAuthor.AuthorID = Author.AuthorID
GROUP BY ArticleAuthor.ArticleID, ArticleAuthor.AuthorID

但它返回重复:

ArticleID Authors
--------- -------
1         XXX YYY AAA
1         MMM NNN BBB

那么,有没有办法删除重复项?我一直在阅读关于模拟GROUP_CONCAT(我的目标是sql server 2008 RC 2),这就是我找到的答案(实际上是在stackoverflow中),但对我来说不起作用(或许多对很多关系,也许)。

好吧,如果有人可以帮助我,我将不胜感激。

提前致谢:)

1 个答案:

答案 0 :(得分:2)

尝试

SELECT ArticleID, 
         STUFF((SELECT DISTINCT ',' + a.AuthorFName + ' ' + a.AuthorMName + ' ' + a.AuthorName 
                  FROM ArticleAuthor aa JOIN Author a 
                    ON aa.AuthorID = a.AuthorID 
                 WHERE aa.ArticleID = aa2.ArticleID 
                   FOR XML PATH('')) , 1 , 1 , '' ) Authors
  FROM ArticleAuthor aa2
 GROUP BY ArticleID

输出:

| ARTICLEID |                 AUTHORS |
---------------------------------------
|         1 | MMM NNN BBB,XXX YYY AAA |

这是 SQLFiddle 演示