簡體   English   中英

引用同一列中的外鍵

[英]Referencing foreign keys in the same column

我正在為 mysql 設計一個 bd-scheme。 我的數據庫存儲 3 種點:a、b 或 c,路徑由 n 對點組成:

Route = [ (a1 or b1 or c1 ; a2 or b2 or c2), (a2 or b2 or c2; a3 or b3 or c3), ...]

create table a_points (
    point_id    serial      not null,
    owner_id    bigint unsigned not null,
    name        varchar(20) not null,

    primary key (point_id),
    foreign key (owner_id) references othertable (other_id)
    ) engine = InnoDB;


create table b_points (
    point_id    serial      not null,
    owner_id    bigint unsigned not null,
    name        varchar(20) not null,
    fields      varchar(20) not null,


    primary key (point_id),
    foreign key (owner_id) references othertable (owner_id)

    ) engine = InnoDB;

create table c_points (
    point_id    serial      not null,
    name        varchar(20) not null,
    cfields     varchar(20) not null,

    primary key (point_id)
    ) engine = InnoDB;

create table paths (
    path_id serial          not null,
    name        varchar(20) not null,

    primary key (path_id)
    ) engine = InnoDB;

create table point_pairs (
    pair_id     serial      not null,
    path_id bigint  unsigned    not null,
    point_from  bigint unsigned not null,
    point_to    bigint unsigned not null,
    table_from  varchar(9)  not null,
    table_to    varchar(9)  not null,

    primary key (pair_id),
    foreign key (path_id) references paths (path_id)
    ) engine = InnoDB;

(*) 一對點是 (m, n) 或從 m 到 n

所以我將一對點與其路徑的 id 一起存儲。 我的問題是我必須創建兩列來標識 m 和 n 的表名稱。 table_from 用於 m,table_to 用於 n。 因此,我必須在我的代碼中使用這兩列來了解路徑中保存了哪些類型的點(路徑和 point_pairs 表)。 我的問題:MySql 是否提供了在同一列中引用 n 個外鍵的東西? 我已經考慮過加入 a、b 和 c 點表,但我必須向這個新表添加一個類型列,我的 php 類將變得無用。

提前致謝!

您正在使用一種稱為多態關聯的模式,不,沒有辦法做到這一點並使用外鍵來強制執行參照完整性。

我建議你制作一張a_pointsb_pointsc_points引用的公共表。 然后您的點對可以引用該公用表。

a_points -->
b_points -->  common_points  <-- point_pairs
c_points -->

換句話說,使多態關聯起作用的方法是反轉引用的方向。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM