-
09-09-2019 - |
题
我正在为 mysql 设计一个 bd 方案。我的数据库存储 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。因此,我必须在代码中使用这两列来了解路线中保存了哪些类型的点(路径和 point_pairs 表)。我的问题:MySql 是否提供了引用同一列中的 n 个外键的功能?我已经考虑过加入 a、b 和 c 点表,但我必须向这个新表添加一个类型列,我的 php 类将变得毫无用处。
提前致谢!
解决方案
您正在使用一种称为多态关联的模式,不,没有办法做到这一点并使用外键来强制引用完整性。
我建议你制作一张公用表 a_points
, b_points
, , 和 c_points
参考。然后您的点对可以引用该公用表。
a_points -->
b_points --> common_points <-- point_pairs
c_points -->
换句话说,让多态关联起作用的方法是反转引用的方向。
不隶属于 StackOverflow