从多个表中删除数据

时间:2013-10-01 13:49:23

标签: sql sql-delete

create table Person(
    SSN INT,
    Name VARCHAR(20),
    primary key(SSN)
);
create table Company(
CompanyID INT,
Name VARCHAR(20)
primary key(SSN)

create table Car(
    PlateNr INT,
    Model VARCHAR(20),
    primary key(PlateNr)
);

create table CarOwner(
    SSN INT,
    PlateNr INT,
    primary key(SSN, PlateNR)
    foreign key(SSN) references Person (SSN),
    foreign key(PlateNr) references Car (PlateNr)
);

create table CompanyWorker(
    SSN INT,
    CompanyID INT
    primary key(SSN, CompanyID),
    foreign key(SSN) references Person (SSN),
    foreign key(CompanyID) references Company (CompanyID)
);

Insert into Person(SSN, Name) VALUES ('123456789','Max');
Insert into Person(SSN, Name) VALUES ('123456787','John');
Insert into Person(SSN, Name) VALUES ('123456788','Tom');

insert into Company(CompanyID, Name) VALUES('1','IKEA');
insert into Company(CompanyID, Name) VALUES('2','Starbucks');

Insert into Car(PlateNr, Model) VALUES ('123ABC','Volvo');
Insert into Car(PlateNr, Model) VALUES ('321CBA','Toyota');
Insert into Car(PlateNr, Model) VALUES ('333AAA','Honda');

Insert into CarOwner(SSN, PlateNr) VALUES ('123456789','123ABC');
Insert into CarOwner(SSN, PlateNr) VALUES ('123456787','333AAA');
Insert into CarOwner(SSN, PlateNr) VALUES ('123456788','321CBA');

insert into CompanyWorker(SSN, CompanyID) VALUES('123456789','1');
insert into CompanyWorker(SSN, CompanyID) VALUES('123456787','1');

这是我的表并插入到这些表中,我遇到的问题是删除一个人。我希望能够从“人员”表中删除一个人,例如

DELETE FROM Person WHERE SSN = '123456789';

但问题是我必须从所有与该人有关系的其他表中删除该人。人与CarOwner和CompanyWorker有关系。当然,我可以一次执行3个单独的删除语句:

DELETE FROM Person WHERE SSN = '123456789';
DELETE FROM CarOwner WHERE SSN = '123456789';
DELETE FROM CompanyWorker WHERE SSN = '123456789';

但是如果这个SSN在CompanyWorker中不存在,我会遇到问题,因为它试图删除那里不存在的东西。因此,我需要以某种方式能够在以某种方式删除之前检查它是否存在,这是我的问题。

1 个答案:

答案 0 :(得分:1)

如果使用MSSQL作为数据库引擎,可以使用ALTER TABLE添加带有ON DELETE CASCADE的FOREIGN CONSTRAINT

ALTER TABLE CarOwner
    ADD CONSTRAINT FK_CarOwner_SSN 
        FOREIGN KEY (SSN) 
        REFERENCES Person (SSN) 
        ON DELETE CASCADE