簡體   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