假设每个客户都有以下架构(只是一个示例) 恰好两个电话号码具有不同的目的:
create table customer (
id integer primary key,
home_phone_id integer not null,
work_phone_id integer not null,
foreign key (home_phone_id) references phone (id),
foreign key (work_phone_id) references phone (id)
);
create table phone (
id integer primary key,
number varchar(10) not null
);
外键放在customer
表中以便区分
家庭和工作电话号码之间。这在技术上
使phone
为“父”表,customer
为孩子,即使是客户
“有”一个电话号码,而不是相反。 (如果没有客户,应用程序将永远不会查询电话号码。)
当客户行被删除时,我希望它的两行来自手机 自动删除。这是从“孩子”到“父母”的级联,而不是 从父母到孩子是正常的。我的印象是没有SQL数据库 支持这种行为。我可以使用触发器来实现这一目标,但我认为 事实上,它不受支持意味着我设计的架构是错误的。
我可以想象两种替代设计,这两种设计看起来都不是很好:
分别创建相同的home_phone
和work_phone
表
使用customer_id
,将customer
设为父级。
通过将外键移动到customer
来使phone
成为父项,然后使用
phone
中的额外列(如布尔值is_home
),用于区分两种类型的电话号码。
设计这个的正确方法是什么?
答案 0 :(得分:0)
选项2将是您最好的选择。通过将customer_id
移至phone
表并添加新的phone_type
字段,您将获得两项直接优势。
CASCADE DELETE
。 phone_type
字段中的实际数据可以是标准化的值列表,例如:主页,工作,单元格