[英]How can I implement the customer and Account table shown in ER diagram in SQL
有了這種關系,您幾乎不需要兩個表。 它們之間存在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.