2

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
)
4

4 回答 4

3
DELETE FROM report_detail
WHERE 
    report_detail.reportId IN
    (
        SELECT reportId 
        FROM report 
        WHERE migrated = 1
    )
于 2010-08-23T16:59:12.573 回答
2

这可能会删除表中的所有内容。

试试这个:

delete d 
from report_detail d 
inner join report r  
    on r.reportId = d.reportId  
where migrated = 1
于 2010-08-23T16:59:45.140 回答
2
delete from report_detail d 
inner join report r 
on r.reportId = d.reportId 
where migrated = 1
于 2010-08-23T17:01:00.800 回答
1

MySQL 有一种方法可以从特定表中删除,同时与其他表连接:

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

或者:

DELETE FROM t1, t2 USING t1 INNER JOIN t2 INNER JOIN t3
WHERE t1.id=t2.id AND t2.id=t3.id;
于 2010-08-23T16:59:18.210 回答