SQL 多对多关系 table

SQL many to many relationship table

我正在尝试在这两个 table 之间建立多对多关系。

CREATE TABLE series (
    title VARCHAR(30),
    language VARCHAR(30),
    year INT,
    PRIMARY KEY (title)
);

CREATE TABLE actors (
    name VARCHAR(30),
    age INT,
    country VARCHAR(30),
    serie VARCHAR(30),
    PRIMARY KEY (name , age , country , serie),
    FOREIGN KEY (serie)
        REFERENCES series (title)
);

我试图创建一个单独的 table 来形成多对多关系。这看起来正确吗?

CREATE TABLE series_actors_combined (
    title VARCHAR(30),
    name VARCHAR(30),
    age INT,
    country VARCHAR(30),
    serie VARCHAR(30),
    FOREIGN KEY (title)
        REFERENCES series (title),
    FOREIGN KEY (name)
        REFERENCES actors (name),
    FOREIGN KEY (age)
        REFERENCES actors (age),
    FOREIGN KEY (country)
        REFERENCES actors (country),
    FOREIGN KEY (serie)
        REFERENCES actors (serie)
   );

您的 table 看起来不对。

作为初学者,您在引用该系列的演员 table 中有一个外键,这基本上违背了桥梁 table 的目的。

此外,从桥 table 到 actors 的外键不是 well-formed:你每列有一个键,而你应该有一个唯一的 multi-column 键来引用演员。我建议使用自动递增的主键而不是使用这些列组合。这为您的设计提供了更大的灵活性(在现实生活中,两个不同的系列 可能 具有相同的标题),并使 much 更容易创建外国桥中的钥匙 table.

考虑:

create table series(
    id int primary key auto_increment,
    title varchar(30) unique,
    language varchar(30), 
    year int
);

create table actors(
    id int primary key auto_increment,
    name varchar(30), 
    dob date,     -- better than age 
    country varchar(30)
);

create table series_actors(
    series_id int references series(id),
    actor_id int references actors(id),
    primary key (series_id, actor_id)
)