我有大约10个表,如: 城市,地区,城镇等都有school_id专栏。
我想删除school_id中与学校表相比没有匹配的所有表中的school_id。我可以轻松地为一张桌子做这件事。像这样:
DELETE FROM cities
WHERE school_id NOT IN (SELECT s.id
FROM schools s)
对于地区表:
DELETE FROM districts
WHERE school_id NOT IN (SELECT s.id
FROM schools s)
我的问题是有没有办法将所有这些查询合二为一?
答案 0 :(得分:0)
您可以使用简单的JOIN
delete a, b from cities a
join districts b using(school_id)
where school_id not in (select id from schools)
为要删除的每个表添加join
。
delete a, b, c from cities a
join districts b using(school_id)
join tables3 c using(school_id)
where school_id not in (select id from schools)