This is probably very easy, but it's Monday morning. I have two tables:
Table1:
Field | Type | Null | Key | Default | Extra
id | int(32) unsigned | NO | PRI | NULL | auto_increment
group | int(32) | NO | | 0 |
Table2:
Field | Type | Null | Key | Default | Extra
group | int(32) | NO | | 0 |
Ignoring other fields...I would like a single SQL DELETE statement that will delete all rows in Table1 for which there exists a Table2.group equal to Table1.group. Thus, if a row of Table1 has group=69, that row should be deleted if and only if there exists a row in Table2 with group=69.
Thank you for any help.
Example - Using EXISTS with the DELETE Statement You may wish to delete records in one table based on values in another table. Since you can't list more than one table in the FROM clause when you are performing a delete, you can use the EXISTS clause.
DELETE FROM ReferencingTable WHERE NOT EXISTS ( SELECT * FROM MainTable AS T1 WHERE T1. pk_col_1 = ReferencingTable. pk_col_1 ); Second, as a one-time schema-alteration exercise, add the ON DELETE CASCADE referential action to the foreign key on the referencing table e.g.
I think this is what you want:
DELETE FROM `table1`
WHERE `group` in (SELECT DISTINCT `group` FROM `table2`)
I think this way is faster:
DELETE FROM t1 USING table1 t1 INNER JOIN table2 t2 ON ( t1.group = t2.group );
The nice solution is just writing the SQL as you say it yourself already:
DELETE FROM Table1
WHERE
EXISTS(SELECT 1 FROM Table2 WHERE Table2.Group = Table1.Group)
Regards, Arno Brinkman
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With