我想从表中删除一些行。
首先,我尝试使用子查询,但是当在子查询中使用同一个表时,我无法从表中删除数据。
我试着用另一种方式做到这一点。
set @list_id_remove = (select group_concat(mra.media_id) from movie AS m
right join media AS mra ON m.id = mra.media_id
where m.id is null);
delete from media
where media_id IN (@list_id_remove);
但在这种情况下查询只删除 1 行。 我认为麻烦 - 是 group_concat 删除字符串,我需要整数列表。
您似乎想从
media
中删除,而movie
中不存在相应的记录。您可以将此作为单个查询来执行。
delete from media
where not exists (select 1 from movie m where m.id = media.media_id);
我觉得字段
movie.id
对应于 media.media_id
确实很奇怪,但这就是您的原始查询的编写方式。
编辑:
至于你的问题,你可以把
delete
写成:
delete from media
where find_in_set(media_id, @list_id_remove) > 0;
对于本文中的案例,存在不使用group_concat 的解决方案。但是在某些情况下,我们会使用 group_concat 来收集令人愉快的记录 ID。
FIND_IN_SET
功能在这种情况下会很方便。
delete
from
media
where
media_id FIND_IN_SET(media_id, (
select
group_concat(mra.media_id)
from movie AS m
right join media AS mra ON m.id = mra.media_id
where
m.id is null
) d
);