好的,所以我是派生表的新手。当我运行这个查询时,它给了我一个MYSQL错误1248.任何人都知道为此工作?这可能是我做过的最复杂的查询,我只想让它工作。谢谢!
delete from table_1
where thing_id in (
select tid from(
select thing_id as tid
FROM table_1
inner join table_2
on table_1.thing_id = table_2.thing_id
where stuff = 'stuff'
)
)
答案 0 :(得分:3)
MySQL通常不允许您在语句的其余部分引用要删除(或更新)的表。你可以使用嵌套的子查询解决这个问题(你似乎正在尝试这样做)。但是,我认为最好使用显式join
来进行更新:
delete t1
from table_1 t1 join
(select t1.thing_id as tid
from table_1 t1 inner join
table_2 t2
on t1.thing_id = t2.thing_id
where stuff = 'stuff'
) tt
on t1.thing_id = tt.tid;
那就是说,我认为这相当于只在join
上执行table2
:
delete t1
from table_1 t1 join
table_2 t2
on t1.thing_id = t2.thing_id;
where stuff = 'stuff';
后一种方法也应具有更好的性能。
答案 1 :(得分:2)
您忘记了表格别名
delete from table_1
where thing_id in (
select tid from(
select table_1.thing_id as tid
FROM table_1
inner join table_2
on table_1.thing_id = table_2.thing_id
where table_1.stuff = 'stuff'
) tmp
)