Delete rows from the second table if the corresponding user is deleted from the first table

时间:2017-10-12 09:57:22

标签: mysql sql

I'm deleting some rows (users) from a table using the following query

DELETE
FROM
    rfs_users
WHERE
    ID > 1 AND user_registered < '2017-05-16 12:09:54' AND user_login NOT IN ('username1', 'username2')

I have another table and I also need to delete some rows from it. This table (rfs_usermeta) has a different structure and I can't use the same query on it.

In rfs_users, one row corresponds to one user. In rfs_usermeta, multiple rows corresponds to one user. I could just use

DELETE FROM rfs_usermeta WHERE user_id > 1

but that would delete almost all rows. I need to delete a user in rfs_usermeta if that user is also to be deleted in rfs_users.

For example:

// loop rows in rfs_users
for (row in rfs_users) {
    // target specific rows
    if (row.user_id > 1 && row.user_registered < '2017-05-16 12:09:54' && !('username1', 'username2').includes(row.user_login)) {
        // delete matching row
        row.remove()
        // also delete rows from rfs_usermeta
        rfs_usermeta.getRows(row.user_id).remove()
    }
}

How do I form this query?

2 个答案:

答案 0 :(得分:2)

Does the usermeta have a Foreign Key Constraint to the users table? If so you can set what happens in the referenced row.

You can automatically remove corresponding rows by adding the foreign key constraint to the usermeta like this:

ALTER TABLE usermeta ADD CONSTRAINT FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE;

This removes all usermeta rows that reference a removed user.

If you do not want to do that you can also add a Trigger to the user table that removes usermeta rows.

Hope this helps ;)

答案 1 :(得分:1)

Run this alter.On delete cascade will automatically take care of this.

alter table rfs_usermeta modify constraint fk_name foreign key (user_id) references rfs_users (ID) on delete cascade;