如何在具有多个联接和条件的查询中从单个表中删除记录?

时间:2018-09-27 18:59:08

标签: mysql

具有以下相关表格

enter image description here

我需要消除table4table1之间的关系,也就是说,{4}的table1_table4与table3的{ {1}}

要确定我编写此查询的受影响的行数

target

在这里,我确定了149条受影响的记录。

现在,我需要删除target中的受影响数据。您能告诉我如何编写此删除查询吗?

预先感谢

2 个答案:

答案 0 :(得分:1)

您可以使用与选择

相同的联接
    DELETE t2.* 
    FROM table2 t2
    INNER JOIN
        table2_table3 ON table2.id = table2_table3.table2_id
            INNER JOIN
        table3 ON table3.id = table2_table3.table3_id
            INNER JOIN
        table1_table2 ON table2.id = table1_table2.table2_id
            INNER JOIN
        table1 ON table1.id = table1_table2.table1_id
            INNER JOIN
        table1_table4 ON table1.id = table1_table4.table1_id
            INNER JOIN
        table4 ON table4.id = table1_table4.table4_id
    WHERE     table3.target != table4.target;

,对于table1_table4,如果连接条件相同,则可以使用

    DELETE table1_table4.*
    FROM table1_table4 
    INNER JOIN
        table2_table3 ON table2.id = table2_table3.table2_id
            INNER JOIN
        table3 ON table3.id = table2_table3.table3_id
            INNER JOIN
        table1_table2 ON table2.id = table1_table2.table2_id
            INNER JOIN
        table1 ON table1.id = table1_table2.table1_id
            INNER JOIN
        table1_table4 ON table1.id = table1_table4.table1_id
            INNER JOIN
        table4 ON table4.id = table1_table4.table4_id
    WHERE     table3.target != table4.target;

答案 1 :(得分:1)

MySQL支持多列IN

delete from table1_table4 where (table1_id, table4_id) in (
 select t14.table1_id, t14.table4_id from
    table2
    INNER JOIN
    table2_table3 ON table2.id = table2_table3.table2_id
    INNER JOIN
    table3 ON table3.id = table2_table3.table3_id
    INNER JOIN
    table1_table2 ON table2.id = table1_table2.table2_id
    INNER JOIN
    table1 ON table1.id = table1_table2.table1_id
    INNER JOIN
    (SELECT * FROM table1_table4) t14 ON table1.id = t14.table1_id
    INNER JOIN
    table4 ON table4.id = t14.table4_id
)

我不是将IN用于长列表的忠实拥护者,但这相对较短

您还将注意到table1_table4被包装在另一个选择中。这样做是为了克服MySQL不允许您修改从中选择的表的限制。此子查询将表具体化为临时表,因此mySQL将其视为与您要更新的表不同的表。作为技巧,它可能无法在MySQL 8中使用-有关更多信息,请参见第一条评论中发布的链接