【问题标题】:Relational schema design: "two-to-one" relationship or "backward delete cascade"关系模式设计:“二对一”关系或“向后删除级联”
【发布时间】:2014-04-08 05:57:53
【问题描述】:

假设我有以下架构(只是一个示例),其中每个客户都有 正好是两个用途不同的电话号码:

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数据库 支持这种行为。我可以使用触发器来完成此操作,但我认为 它不受支持的事实意味着我设计的架构错误。

我可以想象两种可供选择的设计,但似乎都不是很好:

  1. 分别创建相同的 home_phonework_phone 表 使用customer_id,使customer 成为父级。

  2. 通过将外键移动到 phone 使 customer 成为父级,并使用 phone 中的额外列(如布尔值is_home)以区分两种类型的电话号码。

设计这个的正确方法是什么?

【问题讨论】:

  • 选项3:创建第三张表,customer_id,phone_id,中间键入链接

标签: mysql sql database schema schema-design


【解决方案1】:

选项 2 将是您的最佳选择。通过将customer_id 移动到phone 表并添加一个新的phone_type 字段,您可以获得两个直接优势。

  1. 您现在拥有正在寻找的CASCADE DELETE
  2. 这也可以扩展到将来添加更多电话类型。也许您想添加手机、秘书或助理电话号码类型。

phone_type 字段中的实际数据可以是标准化的值列表,例如:homeworkcell

【讨论】:

    猜你喜欢
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 2018-04-26
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 2016-01-17
    • 2017-06-02
    相关资源
    最近更新 更多