0

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

我有 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)

Author 表有 2 个作者:

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

文章:

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

和文章作者

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 中),但对我不起作用(或者可能是多对多关系)。

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

提前致谢 :)

4

1 回答 1

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

输出:

| 文章编号 | 作者 |
--------------------------------------
| 1 | MMM NNN BBB,XXX YYY AAA |

这是SQLFiddle演示

于 2013-08-12T01:51:14.030 回答