0

我有 3 张桌子:

电影数据库

movieID | Title
1       | Star War

StarringDB

movie ID | nameID
1        | 1
1        | 2
1        | 3
1        | 4
1        | 5

名称数据库

nameID | Name
1      | Harrison Ford
2      | Mark Hamill
3      | Carrie Fisher
4      | Peter Cushing
5      | Alec Guinness

我希望输出是:

ID | Title    | Starrings
1  | Star War | Harrison Ford, Mark Hamill, Carrie Fisher, Peter Cushing, Alec Guinness
4

1 回答 1

1

SQL Server 没有为您连接值的函数,因此您可以使用它FOR XML PATH来获取结果:

select m.movieID,
  m.title,
  STUFF((SELECT  ', ' + n.name
         from name n
         inner join starring s
           on n.nameID = s.nameid
         where s.movieID = m.movieID
         group by n.name, n.nameid
         order by n.nameid
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,2,'') starrings
from movie m;

请参阅SQL Fiddle with Demo

或者您可以使用FOR XML PATHand CROSS APPLY

select m.movieID,
  m.title,
  left(c.stars, len(c.stars)-1) stars
from movie m
cross apply
(
  select n.name + ', '
  from name n
  inner join starring s
    on n.nameID = s.nameid
  where s.movieID = m.movieID
  group by n.name, n.nameid
  order by n.nameid
  FOR XML PATH('')
) c (stars);

请参阅带有演示的 SQL Fiddle

于 2013-04-11T18:52:51.560 回答