Delete rows out of table that is innerjoined and unioned with 2 others

Posted by jonathan on Stack Overflow See other posts from Stack Overflow or by jonathan
Published on 2011-01-05T00:35:08Z Indexed on 2011/01/05 0:53 UTC
Read the original article Hit count: 72

Filed under:

We have 3 tables (table1, table2, table3), and I need to delete all the rows from table1 that have the same ID in table2 OR table3. To see a list of all of these rows I have this code:

(
 select 
    table2.ID,
    table2.name_first,
    table2.name_last,
    table2.Collected
 from 
    table2
 inner join 
    table1
 on 
    table1.ID = table2.ID
 where
    table2.Collected = 'Y'
 )

 union

 (
 select
    table3.ID,
    table3.name_first,
    table3.name_last,
    table3.Collected
 from 
    table3
 inner join 
    table1
 on 
    table1.ID = table3.ID
 where
    table3.Collected = 'Y'
 )

I get back about 200 rows. How do I delete them from table1? I don't have a way to test if my query will work, so I'm nervous about modifying something I found online and potentially deleting data (we do have backups, but I'd rather not test out their integrity).

TIA!

© Stack Overflow or respective owner

Related posts about sql