Background:
I have three tables that work together:
- tg_users (primary key is 'userid')
- tg_type1_user (has tg_users.userid as a foreign key and column named 'name')
- tg_type2_user (has tg_users.userid as a foreign key and column named 'name')
A given userid may be associated with one or both user types.
Problem:
I would like to remove any entry from tg_users for which the userid is not associated with either user type. (Ultimately, this will be executed from PHP using mysqli.)
My (non-working) solution:
Create a view named tg_dead_userids with the following definition:
select u.userid, a.name as a_name, b.name as b_name
from tg_users u
left join tg_type1_user a on a.userid=u.userid
left join tg_type2_user b on b.userid=u.userid
;
Perform the cleanup using:
delete from tg_users
where userid in (
select userid
from tg_dead_userids
where a_name is null
and b_name is null
);
... but mysql will not allow me to perform this delete because tg_dead_userids is referencing tg_users.
Suggestions?
I realize that I can perform a query on the tg_dead_userids to find all entries with null a_name and b_name, fetch the resulting list of userids, and loop over the userids to issue a delete statement for each (or create a single delete statement using an 'in' clause).
I was hoping, however, to perform this with a single mysqli transaction.
Any thoughts/suggestions? Or will I need to go with multiple transactions?
Thanks much for any/all help.