开发者

Mysql deleting rows not in other table

I know this is possible, but not when you need to reference the row you want to delete from. For example:

select * from `dvd_role` r
left join `dvd_actor2role` a on a.`roleId` = r.id
where a.roleId is null;

This produces the offending rows which are not present 开发者_C百科in the dvd_actor2role table and I want to delete. But I cannot use the dvd_role table in the subquery or I get an error, yet I need that table to be able to determine which rows to delete.

Is there a workaround for this within SQL?

Thanks.


Left join and checking for null at the "right limb" seems a pathology these days. Use NOT EXISTS instead.

SELECT *
FROM dvd_role r
WHERE NOT EXISTS (
   SELECT * FROM dvd_actor_role a
   WHERE a.roleId = r.id
   );

If all is well replace the first "select *" by a DELETE.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜