Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete based on composite key from another table

I've been really reluctant to post this because I feel it's a common issue, but I can not seem to find an answer that applies to this situation... (maybe I'm just a really bad googler).

I have two identical tables(column wise, not data), table1 and table2. I wish to delete the records in table1 in which the composite key (col1, col2) exists in both tables. Here is what I have, which seems correct to me, but is throwing an error.

DELETE FROM Table1
WHERE (**Col1**, Col2) IN
(SELECT Col1, Col2
FROM Table1 a
JOIN Table2 b
    ON a.Col1 = b.Col1
    AND a.Col2 = b.Col2)

Error:

Msg 4145, Level 15, State 1, Line 212 An expression of non-boolean type specified in a context where a condition is expected, near ','.

I have put two * around the portion of code which has 'Red error squiggles'.

like image 305
Jeff Avatar asked Nov 19 '12 23:11

Jeff


1 Answers

This can be cleanly performed using JOIN with your DELETE:

DELETE a
FROM 
    Table1 a 
    JOIN Table2 b
        ON a.Col1 = b.Col1
        AND a.Col2 = b.Col2
like image 177
Michael Fredrickson Avatar answered Sep 22 '22 06:09

Michael Fredrickson