0

I have two tables, user and ban. User table has two columns id and type. Ban table also has two columns userID and bannedUserID. I want to delete records in ban table where bannedUserID has type of 'Admin'.

I've come up with such query but I am not sure if it is correct or not.

DELETE FROM ban WHERE ban.bannedUserID IN (SELECT id FROM user WHERE type = 'Admin')

Is it correct? Do I have to add/remove anything?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Sarpdoruk Tahmaz
  • 1,418
  • 3
  • 17
  • 25

1 Answers1

4

If you're not sure whether the DELETE is correct, you can test it by converting to an equivalent SELECT:

SELECT b.bannedUserID 
FROM ban b JOIN user u ON b.bannedUserID = u.id
WHERE u.type = 'Admin';

Are the id's returned by that query the ones you want to DELETE?

Then try it in a transaction (if you use a storage engine that supports transactions, i.e. not MyISAM), so you can roll back if necessary:

START TRANSACTION;

DELETE b 
FROM ban b JOIN user u ON b.bannedUserID = u.id
WHERE u.type = 'Admin';

/* do some SELECT to see if the correct rows have been deleted and no others */
/* but if anything appears wrong, and ban is an InnoDB table, you can... */

ROLLBACK;

Note that I'm using MySQL's multi-table DELETE syntax. It should work identically to your subquery approach, but in some cases it can be more flexible.

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828