简体   繁体   中英

MySQL: Delete rows from either of two tables

I have two tables setup like this:

user_users

ID    ColA    ColB
55    This    That
56    Other   Stuff

user_meta

ID    UserID    MetaName    MetaValue
1     56        some_name   some_value
2     56        other_name  other_vaue
3     99        this_too    equals_this

So, there can be multiple rows in the user_meta table attributed to a given UserID . When I remove a user, I need to also remove any rows in the user_meta table attributed to that user.

Here's what I have:

DELETE user_users, user_meta FROM user_users LEFT JOIN user_meta ON user_meta.UserID = user_users.ID WHERE user_users.ID = 56

This will work great in these scenarios:

  1. If the user exists in user_users but no rows exist for this user in user_meta
  2. If the user exists in user_users and rows exist for this user in user_meta

The problem is that if (for some reason) the user ID exists in user_meta but NOT in user_users , the rows are not removed from the user_meta table.

For all practical reasons, this query should work in all cases (because how would you have user meta saved for a nonexistent user?), but just in case, I'd like to ensure that the query would also remove any rows in the user_meta table with the UserID EVEN IF that user does not exist in the user_users table.

So, I'd like this query to remove any rows in the user_meta table with UserID = 99 , but it doesn't, because no ID of 99 exists in the user_users table:

DELETE user_users, user_meta FROM user_users LEFT JOIN user_meta ON user_meta.UserID = user_users.ID WHERE user_users.ID = 99

How do I update this query to delete from either/both tables regardless if the ID exists on either of the other tables?

This situation is a good candidate for using cascading deletion constraints. You want child records in the user_meta table to be deleted whenever a parent record in user_users is deleted. Assuming there is already a foreign key constraint on UserID in the user_meta table, you could try:

ALTER TABLE user_meta DROP FOREIGN KEY user_id_key;

ALTER TABLE user_meta
ADD CONSTRAINT user_id_key
FOREIGN KEY (UserID) REFERENCES user_users (ID)
ON DELETE CASCADE;

This assumes that you already have a foreign key constraint on user_meta#UserID . If you don't, then ignore the first ALTER TABLE statement.

With this constraint in place, deleting a user record from user_users would automatically cause all child records in user_meta to be deleted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM