views:

56

answers:

4

There are 2 tables: report (which has a primary key of reportId and a bit field called migrated) and report_detail (which has a foreign key of reportId). I want to delete all the rows from report_detail that have a reportId which, in the report table, has migrated = 1. This is the select query that selects all the rows I want:

select * 
from report r inner join report_detail d 
    on r.reportId = d.reportId 
where migrated = 1

Will this delete query do what I want or am I doing something wrong?

delete from report_detail
where exists(
    select * 
    from report r inner join report_detail d 
        on r.reportId = d.reportId 
    where migrated = 1
)
+3  A: 
DELETE FROM report_detail
WHERE 
    report_detail.reportId IN
    (
        SELECT reportId 
        FROM report 
        WHERE migrated = 1
    )
Simmo
You can also rephrase this for EXISTS: `WHERE EXISTS(select reportID FROM Report where Migrated=1)` which may run faster depending on how many rows you have in your tables.
JNK
+1  A: 

MySQL has a way to delete from a particular table, while joining with other tables:

DELETE t1, t2 FROM t1 INNER JOIN t2 INNER JOIN t3
WHERE t1.id=t2.id AND t2.id=t3.id;

Or:

DELETE FROM t1, t2 USING t1 INNER JOIN t2 INNER JOIN t3
WHERE t1.id=t2.id AND t2.id=t3.id;
Sjoerd
+2  A: 

That will likely delete everything in your table.

try this instead:

delete d 
from report_detail d 
inner join report r  
    on r.reportId = d.reportId  
where migrated = 1
Russ
Won't this delete everything in both tables that have migrated = 1? I only want to delete from the report_detail table.
dmr
I added the alias so the query would work properly. No it won't delte from both tables only the one specified to delte from.
HLGEM
+2  A: 
delete from report_detail d 
inner join report r 
on r.reportId = d.reportId 
where migrated = 1
Beth