简体   繁体   中英

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

How can I implement the customer and Account table shown in ER diagram in SQL.

  1. Every customer has exactly 1 account.
  2. Every account belongs to exactly 1 customer.
  3. On customer being deleted, the associated account row should also be deleted

在此处输入图片说明

With that relationship, you hardly need two tables. There is a 1-1 relationship between them, even on deleting. That is pretty close to saying that they are the same thing. Normally, a customer would be allowed to have two accounts. Or, customers could exist with no active accounts.

One way is with reflexive foreign key relationships:

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;

(I just used identity() as a convenience for the example.)

However, you'll find that inserting and deleting rows is really tricky because the references in the two tables have to sync up. You can get around this using transactions or triggers, or in some cases using updatable views.

Another method is to have one table be more "dominant" and to share the primary key between them:

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)
    . . .
);

This doesn't quite complete the relationship. This does not guarantee that all customers have a matching account. If you try to put that relationship back in, then you'll have the problem with data modifications.

Finally, you could just create one table, CustomerAccounts . This would really solve your problem. All the columns can go in one table, and the deletes and inserts of the two "entities" would automatically be synchronized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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