@Jan mentioned foreign keys already, but his advice is incomplete.
Seems like you want to delete all associations to a bookmark that does not exist (any more).
Define a foreign key constraint in the form of:
ALTER TABLE person_bookmarks
ADD CONSTRAINT pb_fk FOREIGN KEY (bookmarkid) REFERENCES bookmarks (id)
ON UPDATE CASCADE
ON DELETE CASCADE;
This only allows values in
person_bookmarks.bookmarkid
that exist inbookmarks.id
.ON UPDATE CASCADE
changes corresponding values inperson_bookmarks.bookmarkid
when you change an entry inbookmarks.id
ON DELETE CASCADE
deletes corresponding rows inperson_bookmarks.bookmarkid
when you change an entry inbookmarks.id
.
Other options are available, read the manual.
The ON DELETE CASCADE
clause does automatically, what you are trying to fix manually. Before you can add the fk constraint you'll have to fix it manually once:
DELETE FROM person_bookmarks pb
WHERE NOT EXISTS (SELECT 1 FROM bookmarks b WHERE b.id = pb.bookmarkid);
-- OR NOT EXISTS (SELECT 1 FROM persons p WHERE p.id = pb.personid);
Deletes all rows with non-existing bookmarkid
. Uncomment the last line to get rid of dead persons, too.