这是我到目前为止应该尝试的查询:
DELETE
FROM food_detail
WHERE food_id
IN
(
SELECT DISTINCT food_id FROM food_detail
);
我认为逻辑上不应该是一个问题,因为选择查询会给我一个我将删除的ID列表。
这是我得到的错误:
ERROR 1093 (HY000): You can't specify target table 'food_detail' for update in FROM clause
答案 0 :(得分:2)
你必须在另一个查询中扭曲子查询,如下所示:
DELETE FROM food_detail
WHERE food_id IN (
SELECT * FROM (
SELECT DISTINCT food_id FROM food_detail
) AS t
);
Mysql不允许您在内部查询中引用同一个表。
答案 1 :(得分:2)
你想做什么?
您的查询将删除表格中的所有非空food_id
。
我怀疑您要删除仅出现一次的所有food_id
。如果是,请将delete
与join
:
DELETE fd
FROM food_detail fd JOIN
(select food_id
from food_detail fd
group by food_id
having count(*) = 1
) fd1
on fd.food_id = fd1.food_id;
您也可以对原始查询使用相同的方法:
DELETE fd
FROM food_detail fd JOIN
(select distinct food_id
from food_detail fd1
)
on fd.food_id = fd1.food_id;
但这似乎是一种麻烦的说法:
DELETE food_detail
WHERE food_id is not null;