在同一列中引用外键

时间:2009-04-17 04:20:22

标签: mysql database-design polymorphic-associations

我正在为mysql设计一个bd-scheme。我的数据库存储3种点:a,b或c,路径由n对点组成:

路线= [(a1或b1或c1; a2或b2或c2),(a2或b2或c2; a3或b3或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。因此,我必须在代码中使用这两列来了解路径中保存了哪种点(path和point_pairs表)。我的问题:MySql是否提供了在同一列中引用n个外键的东西?我已经考虑过加入a,b和c点表但是我必须在这个新表中添加一个类型列,我的php类将变得无用。

提前致谢!

1 个答案:

答案 0 :(得分:3)

你正在使用一种名为Polymorphic Associations的模式,不,没有办法,并且使用外键来强制引用完整性。

我建议您制作一个a_pointsb_pointsc_points引用的公用表格。然后你的点对可以引用那个公用表。

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

换句话说,使多态关联工作的方法是反转参考的方向。