Reputation: 489
How can I implement the customer and Account table shown in ER diagram in SQL.
Upvotes: 0
Views: 3300
Reputation: 1271241
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.
Upvotes: 0