I basically created some tables to play around with: I have Two main tables, and a Many-Many join table. Here is the DDL: (I am using 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);
I want to create a delete statement that deletes orphans from JOB (if there exists only one entry in the join table for a specific job) based on the PERSON.PERSON_ID.
In pseudo language:
delete from job where job_person.job_id=job.job_id AND count(job_person.job_id)=1 AND job_person.person_id=X
Where X is some person_id. I have tried a lot of different ways; I think it is the ‘COUNT’ part that is causing problems. I am an SQL rookie, so any help would be much appreciated.
I’m not following.
You cannot delete
JOBrows which haveJOB_PERSONrows (even one) because of your FK contraints. Thus there is no way to deleteJOBrows based onPERSONrows.JOB_PERSONrows have to be deleted before either aJOBorPERSONcan be deleted.If you want to delete all
JOBrows with noJOB_PERSON, then one way is:If you want to delete all
JOB_PERSONrows for a particular person and then all orphans, do it in two steps:If you want to delete only the orphan
JOBs previously linked to X, you will need to hold those in a temporary table before the first delete.