我有三张桌子:
book_shelf
- > pkid
和其他列
book_author
- > pkid
,fkid_book_shelf
,fkid_author
author
- > pkid
,name
等
对于book_shelf
中想要以逗号分隔的作者姓名的行。如果书架实体有两个作者,则在book_author
表中插入两行。
这是我试过的
(select BookShelf.pkid as SrNo,stuff((select ',' + a.name
from
lib.book_shelf bs inner join
lib.book_author ba on bs.pkid=ba.fkid_book_shelf
inner join lib.author a on a.pkid=ba.fkid_authors
for xml path ('')
), 1, 1, '') as Author from lib.book_shelf BookShelf)
但它会为每个book_shelf
行选择所有作者姓名。
答案 0 :(得分:1)
希望这可以帮到你。
CREATE TABLE BookShelf(ID INT)
CREATE TABLE BookAuthor(ID INT, BookShelf INT, AuthorID INT)
CREATE TABLE Author(ID INT, Name VarChar(50))
GO
INSERT INTO BookShelf VALUES(1)
INSERT INTO BookShelf VALUES(2)
INSERT INTO Author VALUES(1,'Author1')
INSERT INTO Author VALUES(2,'Author2')
INSERT INTO Author VALUES(3,'Author3')
INSERT INTO Author VALUES(4,'Author4')
INSERT INTO BookAuthor VALUES(1,1,1)
INSERT INTO BookAuthor VALUES(1,1,2)
INSERT INTO BookAuthor VALUES(1,2,3)
INSERT INTO BookAuthor VALUES(1,2,4)
SELECT
BookShelf.ID,
STUFF((SELECT ',' + Author.Name FROM BookAuthor INNER JOIN Author ON BookAuthor.AuthorID = Author.ID WHERE BookAuthor.BookShelf = BookShelf.ID FOR XML PATH('')),1,1,'')
FROM
BookShelf