从多个表中删除行作为一个查询

时间:2015-08-03 04:16:44

标签: mysql

我正在运行以下删除语句,我想知道是否有可能以某种方式组合它们:

DELETE from schools where visibility like 'revoked'

DELETE FROM bookmark_schools
WHERE school_id NOT IN (SELECT s.id FROM school s)

DELETE FROM school_addresses 
WHERE school_id NOT IN (SELECT s.id FROM school s)

DELETE FROM school_highlights 
WHERE school_id NOT IN (SELECT s.id FROM school s)

DELETE FROM school_images 
WHERE school_id NOT IN (SELECT s.id FROM school s)

...

依此类推我喜欢这样的15个查询。是否可以一起运行它们而不是单独运行它们?

5 个答案:

答案 0 :(得分:0)

你有可能,但是一个接一个。但问题是你是想在服务器上运行它还是用某种脚本语言运行它。

答案 1 :(得分:0)

您可以加入查询,如下所示:

DELETE FROM bookmark_schools
FROM            bookmark_schools CROSS JOIN
                         school_addresses CROSS JOIN
                         school_highlights CROSS JOIN
                         school_images CROSS JOIN
                         schools CROSS JOIN
                         school
WHERE        (NOT (bookmark_schools.school_id IN
                             (SELECT        id
                               FROM            school AS s))) AND (NOT (school_addresses.school_id IN
                             (SELECT        id
                               FROM            school AS s))) AND (NOT (school_highlights.school_id IN
                             (SELECT        id
                               FROM            school AS s))) AND (NOT (school_images.school_id IN
                             (SELECT        id
                               FROM            school AS s))) AND (schools.visibility LIKE N'revoked')

答案 2 :(得分:0)

你可以达到你想要的效果,但有一些条件如下 -

第1步:表格引擎应该是innodb,因为在myisam中不起作用。

第二步:创建外键引用意味着所有子表如bookmark_schools,school_Addresses等都有一个主表学校的参考,并且删除了级联。

步骤3:现在您只需要从主表即学校中删除行,并且将从所有子表中删除外键检查。

此外,您可以从here获取帮助。

答案 3 :(得分:0)

要使用单个查询从多个表中删除行,您必须在两个表上创建INNER JOIN。请参阅此question

答案 4 :(得分:0)

您可以将其组合为单个语句,如其他人所指出的那样,但请注意,这仍然是单线程操作。

如果您的目标是提高性能/并行化此操作,您可能需要编写一个脚本来创建15个不同的客户端线程以同时运行语句。