如何连接2个外键列?

时间:2019-05-20 14:53:01

标签: sql .net sql-server sql-server-2012

我有2桌电影和演员。电影表有2列,分别是actor 1和actor 2,它们是具有所有actor的Actor表的外键。

SELECT查询中,我想将actor 1和actor 2都显示为一列 例如(Actor1,Actor2)

电影桌

Id     MovieName   Producer   Actor1    Actor2
1         X-man      prod1     1           2
2         Ant        Prod2     3           1

演员表

Id  ActorName
1     Sam
2     Jhon
3     Brick

我想要的结果

Id     MovieName   Producer      Actors
1         X-man      prod1     Sam , Jhon
2         Ant        Prod2     Brick,Sam

2 个答案:

答案 0 :(得分:1)

要按照要求回答您的问题,您需要两次连接到Actor表,类似select Movie.id, MovieName, Producer, a1.Name+', '+a2.name as 'Actors' from Movie INNER JOIN Actor a1 on Actor1 = a1.id INNER JOIN Actor a2 on Actor2 = a2.id

但是,正如注释中所指出的那样,理想情况下,您应该更规范化数据,以便表结构类似于

CREATE TABLE Movie(
    Id int PRIMARY KEY,
    MovieName nvarchar(50),
    Producer nvarchar(50)
    );

CREATE TABLE Actor(
    Id int PRIMARY KEY,
    Name nvarchar(50)
    );

CREATE TABLE MovieActor(
    Id int PRIMARY KEY
    ActorId int,
    MovieId int);

答案 1 :(得分:0)

您可以尝试以下方法:

Declare @movie table (id int, moviename varchar(50),producer varchar(50),actor1 int, actor2 int)

Declare @Actor table (Id int, Actorname varchar(50))

Insert into @movie values (1,'X-Man','Prod1',1,2)
Insert into @movie values (2,'ANt Man','Prod2',3,1)

insert into @Actor values (1,'Sam')
insert into @Actor values (2,'Jhon')
insert into @Actor values (3,'Brick')


select * from @Actor

select a.id,a.moviename,a.producer,b.Actorname + ',' + c.Actorname as actors from @movie a

join  @Actor b

on a.actor1=b.Id  

join @Actor c on c.Id=a.actor2