繁体   English   中英

如何在SQL中实现ER图中显示的客户和客户表

[英]How can I implement the customer and Account table shown in ER diagram in SQL

如何在SQL中实现ER图中显示的客户和客户表。

  1. 每个客户只有一个帐户。
  2. 每个帐户恰好属于1个客户。
  3. 在删除客户时,关联的帐户行也应删除

在此处输入图片说明

有了这种关系,您几乎不需要两个表。 它们之间存在1-1的关系,即使删除也是如此。 这几乎可以说它们是同一回事。 通常,将允许一个客户拥有两个帐户。 或者,客户可能没有活动帐户就存在。

一种方法是使用反身外键关系:

create table customers as (
    customerId identity(1, 1) primary key,
    accountId int not null,
    . . .
);

create table accounts as (
    accountId identity(1, 1) primary key
    customerId int not null references customers(customerId)
    . . .
);

alter table customers add foreign key (accountId) references accounts(accountId) on delete cascade;

(为了方便起见,我只是使用identity() 。)

但是,您会发现插入和删除行确实很棘手,因为两个表中的引用必须同步。 您可以使用事务或触发器,或者在某些情况下使用可更新的视图来解决此问题。

另一种方法是让一个表更“占优势”,并在它们之间共享主键:

create table customers as (
    customerId identity(1, 1) primary key,
    accountId int not null,
    . . .
);

create table accounts as (
    customerId int primary key references customers(customerId)
    . . .
);

这还不很完整。 这不能保证所有客户都具有匹配的帐户。 如果您尝试重新建立该关系,那么数据修改就会出现问题。

最后,您可以只创建一个表CustomerAccounts 这确实可以解决您的问题。 所有列都可以放在一个表中,并且两个“实体”的删除和插入将自动同步。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM