【问题标题】:Referencing foreign keys in the same column在同一列中引用外键
【发布时间】:2009-04-17 04:20:21
【问题描述】:

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

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

提前致谢!

【问题讨论】:

    标签: mysql database-design polymorphic-associations


    【解决方案1】:

    您正在使用一种称为多态关联的模式,不,没有办法做到这一点并使用外键来强制引用完整性。

    我建议你制作一张 a_pointsb_pointsc_points 参考的通用表。然后您的点对可以引用该公用表。

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

    换句话说,使多态关联起作用的方法是反转引用的方向。

    【讨论】:

    • 这是对我在其他讨论中所说的“泛化专业化模式”的一个很好的总结。我将不得不学习多态关联。
    • @Walter Mitty:前几天我看到你提到过。我想你是唯一一个使用这个短语的人。多态关联是 Hibernate、Ruby on Rails 等中使用的术语。
    • a_pointsb_pointsc_points 中使用PRIMARY KEYs 作为PRIMARY KEYs 并在common_points 中使用与PRIMARY KEY 相同的GUID 是否也是一个好主意?这样,我就可以拥有一张表meta,它可以充当所有多态关联的中间人。
    • @paulkon,使用相同的主键值是个好主意,但我不会说使用 GUID 是个好主意。有关使用 GUID 主键效率低下的演示,请参阅此博客:percona.com/blog/2015/04/03/…
    猜你喜欢
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    相关资源
    最近更新 更多