Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Delete Rows Based on Another Table

Tags:

sql

mysql

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.

like image 967
nedblorf Avatar asked Nov 23 '09 15:11

nedblorf


People also ask

How do you delete a row from a table based on another table?

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.

How do I delete a row in a table that contains foreign keys to other tables?

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.


3 Answers

I think this is what you want:

DELETE FROM `table1`
WHERE `group` in (SELECT DISTINCT `group` FROM `table2`)
like image 143
Jay Avatar answered Oct 08 '22 03:10

Jay


I think this way is faster:

DELETE FROM t1 USING table1 t1 INNER JOIN table2 t2 ON ( t1.group = t2.group );
like image 40
BT26 Avatar answered Oct 08 '22 03:10

BT26


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

like image 26
ArnoBrinkman Avatar answered Oct 08 '22 03:10

ArnoBrinkman