创建足够的数据库

问题描述

在阅读本文时,请查看附件。谢谢!它是纯粹为视觉输入而创建的

我目前正在为一个项目创建数据库,但遇到了这个问题:

我想使用我称为Doctype的名称来区分文档的data_fields。例如,当合同上传时,我想使用具有唯一列的特定表。如表Data_field_1。但是,如果Doctype是收据,我希望它使用表Data_field_2对其字段进行自定义

我知道这样做会有问题。因此,我的问题是:这个问题有可能解决的办法吗?

enter image description here

enter image description here

解决方法

似乎您需要实现“表继承”。有大约四种不同的策略可以做到这一点。我将展示最常见的一种,我个人认为这是最灵活,最安全的一种。

我会假设您的子表是互斥的,因为这是最常见的情况。例如,您可以执行以下操作:

create table Documentation (
  id int primary key not null,title varchar(100)
);

create table DocType ( -- this is the parent table
  id int not null,type char(1) not null check (type in ('c','r','s','o')),data_field int,name varchar(50),primary key (id,type),foreign key (data_field) references Documentation (id)
);

create table Contract ( -- this is a child table "Contract"
  id int not null,type char(1) not null check (type = 'c'),start_date date,end_date date,foreign key (id,type) references DocType (id,type)
);

create table Receipt ( -- this is a child table "Receipt"
  id int not null,type char(1) not null check (type = 'r'),buyer varchar(20),seller varchar(20),type)
);

然后,您可以尝试插入一些数据:

insert into Documentation (id,title)
  values (123,'First Document');

insert into DocType (id,type,data_field,name)
  values (1001,'c',123,'Contract #1');  

insert into Contract (id,start_date,end_date)
  values (1001,'2020-01-01','2020-12-31');

最后,由于我们被强制实行排他性,我尝试为无法使用的DocType插入“收据”(按预期):

insert into Receipt (id,buyer,seller) 
  values (1001,'buyer1','seller2');

错误:ER_NO_REFERENCED_ROW_2:无法添加或更新子行:外键约束失败(testReceipt,CONSTRAINT Receipt_ibfk_1外键(id,{{ 1}})参考typeDocTypeid))

请参见DB Fiddle上的运行示例。