SQL如何处理多对多的关系

时间:2012-05-22 00:33:12

标签: sql database many-to-many relationship

我有两张表有很多关系的表:

Player(personID, school)
Team(teamID, name)

我将使用什么代码来创建名为playerTeam的关联实体表。

我尝试了以下内容:

CREATE TABLE
(
playerID INT NOT NULL, 
teamID INT NOT NULL,
PRIMARY KEY(playerID, teamID)
);

我不知道在这个例子中如何连接表。

2 个答案:

答案 0 :(得分:5)

试试这个:

CREATE TABLE teamPlayer
(
playerID INT NOT NULL, 
teamID INT NOT NULL,
PRIMARY KEY(playerID, teamID)
);

alter table teamPlayer
add constraint 
    fk_teamPlayer__Player foreign key(playerID) references Player(personID);

alter table teamPlayer
add constraint 
    fk_teamPlayer__Team foreign key(teamID) references Team(teamID);

或者这个:

CREATE TABLE teamPlayer
(
playerID INT NOT NULL, 
teamID INT NOT NULL,
PRIMARY KEY(playerID, teamID),

constraint fk_teamPlayer__Player
foreign key(playerID) references Player(personID),

constraint fk_teamPlayer__Team 
foreign key(teamID) references Team(teamID)

);

如果您不需要明确命名外键,可以使用:

CREATE TABLE teamPlayer
(
playerID INT NOT NULL references Player(personID), 
teamID INT NOT NULL references Team(teamID),
PRIMARY KEY(playerID, teamID)
);

所有主要的RDBMS在关系DDL上都非常符合ANSI SQL。每个人都是一样的

CREATE THEN ALTER(显式命名的外键):

CREATE(显式命名的外键):

CREATE(自动命名的外键):

答案 1 :(得分:0)

创建表时不指定某种关系,除非您使用的是FOREIGN KEY。 在您的情况下,您实际上在查询中缺少表名,它应该是那样的

CREATE TABLE `playerTeam`
(
`playerID` INT NOT NULL, 
`teamID` INT NOT NULL,
PRIMARY KEY(`playerID`, `teamID`)
);