I have two different kinds of document. One is organized by folder. The other is organized by client. Here is the table structure, in mysql:
Table docs
ID
title
Table folderDocs
docID -> docs(ID)
folderID -> folders(ID) ON DELETE CASCADE
Table clientDocs
docID -> docs(ID)
clientID -> clients(ID) ON DELETE CASCADE
I am looking for an elegant way to delete documents automatically when either a folder or a client is deleted. The above cascade rules don't quite accomplish this. (Ie the rows in folderDocs will be deleted, but the corresponding rows in docs will remain.)
Is there anyway to set this up in mysql, using cascade rules or some other method, so that when a row from folderDocs or clientDocs is deleted by cascade, the corresponding row in docs is also deleted? (I am hoping to avoid having to programatically delete the documents first, then delete the folder / client.)
Thanks (in advance) for your help.
Assuming that each document must belong to a folder or a client, then you may want to setup a scheduled cleanup job to delete all documents which do not have folders and clients using the query below
DELETE FROM docs USING docs
LEFT JOIN clientDocs c ON (c.docid = docs.id)
LEFT JOIN folderDocs f ON (f.docid = docs.id)
WHERE ISNULL(c.clientid) AND ISNULL(f.folderid)