Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Delete with Subquery

I'm trying to delete from a table with the results of a subquery. The results return a unique tuple, and currently I end up deleting more than just the results returned because i'm only checking col1 results.

DELETE FROM Table1 exTable
WHERE exTable.col1 = ... AND exTable.col2 = ...
(SELECT col1, col2
FROM ...)
like image 312
kshreve Avatar asked Feb 04 '26 09:02

kshreve


2 Answers

Use a join to match more than 1 column.

DELETE t1
FROM Table1 t1
inner join 
(
   select col1, col2 
   from other_table 
   where ...
) t2 on  t2.col1 = t1.col1 
     and t2.col2 = t1.col2
like image 162
juergen d Avatar answered Feb 07 '26 01:02

juergen d


DELETE JOIN is not part of the standard. A sub-query must be declared either with a USING or WITH statement. Below an example with the former.

DELETE  
  FROM Table1 t1
 USING (SELECT c1, c2, ...
          FROM Table2
         WHERE ...
       ) t2
 WHERE t1.c1 = t2.c1
   AND t2.c2 = t2.c2
;
like image 37
Luís de Sousa Avatar answered Feb 06 '26 23:02

Luís de Sousa