在 MySQL 中组合复合外键?

Combine Composite foreign keys in MySQL?

考虑3 tablesMySQLT1, T2, A

T1 -> t1_id as pk, a_id
T2 -> t2_id as pk, a_id
A -> a_id

现在,我需要为(T1T2)创建映射 table,这样

  1. 我只能映射 t1_idt2_id 具有相同的 a_id
  2. 映射应该是多对多
  3. t1_idt2_id 的映射应保持 唯一。

映射table看起来像。

M_T1_T2 -> map_id as pk, a_id, t1_id, t2_id

Question: What foreign key constraints are supposed to be added?

t1 中对 t1_id, a_idt2 中的 t2_id, a_id 设置唯一约束。这些对无论如何都是唯一的,因为 t1_idt2_id 是主键,因此是唯一的。但是需要这样的约束才能允许外键引用这样的一对。

然后在你的链接 table 中,我们称它为 t1_t2,有 t1_idt2_ida_id 以及两个外键 t1_id, a_idt1 中引用 t1_id, a_idt2_id, a_idt2 中引用 t2_id, a_id。也就是说,a_id 在两个引用记录中必须相同。

要强制三元组 t1_id, t2_id, a_id 是唯一的,请对它们设置唯一约束或仅将它们声明为主键。

CREATE TABLE a
             (a_id integer,
              PRIMARY KEY (a_id));

CREATE TABLE t1
             (t1_id integer,
              a_id integer,
              PRIMARY KEY (t1_id),
              FOREIGN KEY (a_id)
                          REFERENCES a
                                     (a_id),
              UNIQUE (t1_id,
                      a_id));

CREATE TABLE t2
             (t2_id integer,
              a_id integer,
              PRIMARY KEY (t2_id),
              FOREIGN KEY (a_id)
                          REFERENCES a
                                     (a_id),
              UNIQUE (t2_id,
                      a_id));

CREATE TABLE t1_t2
             (t1_id integer,
              t2_id integer,
              a_id integer,
              PRIMARY KEY (t1_id,
                           t2_id,
                           a_id),
              FOREIGN KEY (t1_id,
                           a_id)
                          REFERENCES t1
                                     (t1_id,
                                      a_id),
              FOREIGN KEY (t2_id,
                           a_id)
                          REFERENCES t2
                                     (t2_id,
                                      a_id));