tags:

views:

18096

answers:

4

Scenario:

Let's say I have two tables, TableA and TableB. TableB's primary key is a single column (BId), and is a foreign key column in TableA.

In my situation, I want to remove all rows in TableA that are linked with specific rows in TableB: Can I do that through joins? Delete all rows that are pulled in from the joins?

DELETE FROM TableA 
FROM
   TableA a
   INNER JOIN TableB b
      ON b.BId = a.BId
      AND [my filter condition]

Or am I forced to do this:

DELETE FROM TableA
WHERE
   BId IN (SELECT BId FROM TableB WHERE [my filter condition])

The reason I ask is it seems to me that the first option would be much more effecient when dealing with larger tables.

Thanks!

+31  A: 
DELETE TableA 
FROM TableA a
INNER JOIN
TableB b on b.Bid = a.Bid
and [my filter condition]

should work

TheTXI
I used And [my filter condition] on the join instead of a Where clause. I would imagine both would work, but the filter condition on the join will limit your results from the join.
TheTXI
Looks like I should have tried the query before posting. I was concerned because it wasn't actually deleting anything... but it doesn't look like the 2nd method is deleting anything either... must be a server issue
John
Nevermind; it was just taking an excessive amount of time
John
One question. Why do we need to write 'DELETE TableA FROM' instead of 'DELETE FROM'? I see it works only in this case, but why?
+5  A: 

Yes you can. Example :

DELETE TableA 
FROM TableA AS a
INNER JOIN TableB AS b
ON a.BId = b.BId
WHERE [filter condition]
Diadistis
+8  A: 

I would use this syntax

Delete a 
from TableA a
Inner Join TableB b
on  a.BId = b.BId
WHERE [filter condition]
cmsjr
A: 

It's almost the same in MySQL, but you have to use the table alias right after the word "DELETE":

DELETE a
FROM TableA AS a
INNER JOIN TableB AS b
ON a.BId = b.BId
WHERE [filter condition]
Michael Butler