tags:

views:

293

answers:

8

lets say i have tables a and b. b contains items that exist in table a. I want to be able to delete items in a that are in be. What would the sql look like?

A: 

delete a --select a.* from tablea a join tableb b on a.someid = b.someid

make sure you run the selct part first to ensure that you are getting the records you want.

HLGEM
+2  A: 

Something like:

DELETE FROM TableA as A WHERE A.ID IN (SELECT ID FROM TableB AS B WHERE [your condition here])

Pwninstein
+5  A: 

this is an option

delete from a
where a.key in (select key from b)
Victor
+3  A: 

Either:

DELETE a
WHERE a.some_field IN (SELECT some_field FROM b)

or

DELETE A
WHERE EXISTS (SELECT 1 FROM b WHERE b.field1 = a.field2)

Depending on your database, you may find one works particularly better than the other. IIRC Oracle tends to prefer WHERE EXISTS to IN but this can depend on a number of factors.

cletus
+1  A: 

If your tables use InnoDB, the easiest way would be to setup table A with foreign keys from table B, and use ON DELETE CASCADE. That way no code changes are necessary, and the integrity of your database is guaranteed.

Taeram
This also works in just about every other non-mySQL DBMS.
jmucchiello
A: 
DELETE FROM FIRST_TABLE FT
WHERE EXISTS(
            SELECT 1
            FROM SECOND_TABLE ST
            WHERE ST.PRIMARY_KEY = FT.PRIMARY_KEY
            );
JosephStyons
+2  A: 

In certain DBs the rather exotic looking DELETE FROM FROM is very efficient

delete from foo from foo as f
where exists 
(
  select 1 from bar as b  where b.field = f.field
)
annakata
Which DB systems? What does it do?
Tomalak
Ah, I see. That's equivalent to the UPDATE FROM syntax on SQL Server.
Tomalak
Definitely worked on MSSQL 2K and I think 2K5 - googling "delete from from" yields some interesting results
annakata
EXISTS is *so* much more efficient than IN...
annakata
+1 ... never heard of DELETE FROM FROM before, but I've definitely had cases where I could have used it. Now I know! Thanks.
Ian Varley
+1  A: 

This is allowed according to the standard.

delete a from a join b on a.id = b.id;
OIS
+1 Thanks, this one worked for me on a similar problem I encountered today.
Mr Roys