SQL:复杂删除

时间:2008-11-07 14:20:36

标签: sql count hsqldb

我基本上创建了一些表来玩:我有两个主表,还有一个很多连接表。这是DDL :(我使用的是HSQLDB)

CREATE TABLE PERSON
(
    PERSON_ID INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, 
    NAME VARCHAR(50), MAIN_PERSON_ID INTEGER
)

CREATE TABLE JOB
(
    JOB_ID INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, 
    NAME VARCHAR(50)
)
CREATE TABLE JOB_PERSON
(
    PERSON_ID INTEGER, 
    JOB_ID INTEGER
)
ALTER TABLE JOB_PERSON ADD 
    CONSTRAINT FK_PERSON_JOB FOREIGN KEY(PERSON_ID) 
    REFERENCES PERSON ON DELETE CASCADE ON UPDATE CASCADE 

ALTER TABLE JOB_PERSON ADD
    CONSTRAINT FK_JOB_PERSON FOREIGN KEY(JOB_ID) 
    REFERENCES JOB ON DELETE CASCADE ON UPDATE CASCADE

ALTER TABLE PERSON ADD
    CONSTRAINT FK_PERSON_PERSON FOREIGN KEY(MAIN_PERSON_ID) 
    REFERENCES PERSON ON DELETE CASCADE ON UPDATE CASCADE

insert into person values(null,'Arthur', null);
insert into person values(null,'James',0);
insert into job values(null, 'Programmer')
insert into job values(null, 'Manager')
insert into job_person values(0,0);
insert into job_person values(0,1);
insert into job_person values(1,1);

我想基于PERSON.PERSON_ID创建一个删除来自JOB孤立的删除语句(如果特定作业的连接表中只有一个条目)。

伪语言:

delete from job where job_person.job_id=job.job_id 
AND count(job_person.job_id)=1 AND job_person.person_id=X

其中X是某个person_id。我尝试了很多不同的方法;我认为这是造成问题的“COUNT”部分。我是一个SQL菜鸟,所以任何帮助都会非常感激。

2 个答案:

答案 0 :(得分:2)

我不是在跟踪。

由于您的FK限制,您无法删除JOB行(甚至一行)的JOB_PERSON行。因此,无法根据JOB行删除PERSON行。

在删除JOB_PERSONJOB之前,必须删除

PERSON行。

如果您要删除所有JOB行而没有JOB_PERSON,那么一种方法是:

DELETE FROM JOB
WHERE JOB_ID NOT IN (
    SELECT JOB_ID
    FROM JOB_PERSON
)

如果要删除特定人员的所有JOB_PERSON行,然后删除所有孤儿,请分两步执行:

DELETE FROM JOB_PERSON
WHERE PERSON_ID = X

DELETE FROM JOB
WHERE JOB_ID NOT IN (
    SELECT JOB_ID
    FROM JOB_PERSON
)

如果您只想删除以前链接到X的孤儿JOB,您需要在第一次删除之前将它们保存在临时表中。

INSERT INTO TEMP_TABLE
SELECT JOB.JOB_ID
FROM JOB
INNER JOIN JOB_PERSON
    ON JOB_PERSON.JOB_ID = JOB.JOB_ID
WHERE JOB_PERSON.PERSON_ID = X

DELETE FROM PERSON
WHERE PERSON_ID = X

-- YOUR CASCADING DELETE DOES THIS:
/*
DELETE FROM JOB_PERSON
WHERE PERSON_ID = X
*/

-- Now clean up (only) new orphans on the other side
DELETE FROM JOB
WHERE JOB_ID NOT IN (
    SELECT JOB_ID
    FROM JOB_PERSON
)
AND JOB_ID IN (
    SELECT JOB_ID
    FROM TEMP_TABLE
)

答案 1 :(得分:1)

这将删除表JOB_PERSON(Orpheans)中没有条目的表JOB条目。

DELETE FROM JOB
WHERE JOB_ID NOT IN (
    SELECT JOB_ID
    FROM JOB_PERSON
)

您无法删除其他表格上由外国人链接的行...