For example I have 4 tables, all with say userID (which can be referenced more than once. So for example I can have:
Cars
id, ..., userID // userID = owner of the car
Garages
id, ..., userID // userID = owner of the garage
Tools
id, ..., userID // userID = owner of the tool
Now I want to do a query to delete the user, but I only want to delete the user if all their related data is gone. In other words, I want to make sure there is no referenced data (let’s say I’m not allowed to have userID = -1 or null. It has to be assigned to a user
The only way I can see to do the checks is:
SELECT count(*) FROM Cars WHERE USERID = userID
SELECT count(*) FROM Garages WHERE USERID = userID
SELECT count(*) FROM Tools WHERE USERID = userID
Where I have to check if any of the results is greater than 0. Is there a way to do this check across N tables in one SQL SELECT query?
If you want to prevent deleting of users that still have cars, garages or tools you should add a foreign key from those tables to the user table.
If you then try to delete a user which is still referenced you’ll get an error which you can catch and deal with, e.g. by displaying an approriate error message to the user.
This has the added benefit that the deletion will always be prevented, regardless on how someone tries to delete a user (SQL commandline, a buggy piece of code in your application, …)