如果没有NULL值,如何删除内部/左连接的mysql数据库中的行

时间:2018-01-30 21:58:10

标签: php mysql join

我有一张看起来像这样的表:

id_1 | col_1 | col_2
1    | 450   | 2018-01-30 21:38:00
2    | 111   | 2018-01-30 22:18:00
3    | 222   | 2018-01-31 22:18:00

,第二个表格如下:

id_2 | id_1 | beginn              | outdated    
1    | 1    | 2018-01-30 11:38:00 |  0
2    | 1    | 2018-01-30 12:18:00 |  1   <===== THIS ROW IS OUTDATED
3    | 1    | 2018-01-30 13:38:00 |  0
4    | 2    | 2018-01-30 14:18:00 |  0
5    | 3    | 2018-01-30 15:38:00 |  1   <===== THIS ROW IS OUTDATED
6    | 2    | 2018-01-30 16:18:00 |  0

如果没有任何有效的连接,我怎么能删除table1和table2中的值(只有一个查询)。例如从table1中删除id_1 = 3的行,从table2中删除id_2 = 5的行但不是table1中的行,其中id_1 = 1,因为table2中仍有可以连接的条目。

我尝试了以下操作,但它不起作用:

DELETE a,b FROM table1 a 
LEFT JOIN table2 b on a.id_1=b.id_1     
WHERE b.outdated=1 
AND NOT EXISTS (
    SELECT c.id_1 from table1 c 
    INNER JOIN table2 d on c.id_1=d.id_1 
    WHERE d.outdated=0)

如何更改查询或可以为我的意图选择更快的查询

1 个答案:

答案 0 :(得分:1)

我不确定在一个查询中是否有办法执行此操作。这很接近:

DELETE a, b
FROM Table1 AS a
LEFT JOIN Table2 AS b ON a.id_1 = b.id_1
LEFT JOIN Table2 AS c ON a.id_1 = c.id_1 AND c.outdated = 0
WHERE c.id_1 IS NULL
AND (b.id_1 IS NULL -- no match
    OR b.outdated = 1)

但它不会从id_2 = 2删除Table2

我认为可能需要在两个查询中完成:首先删除Table1中不与outdated = 0中的任何Table2行相关联的所有行,然后删除所有过时的内容Table2中的行。

DELETE a
FROM Table1 AS a
LEFT JOIN Table2 AS b ON a.id_1 = b.id_1 AND b.outdated = 0
WHERE b.id_1 IS NULL;

DELETE FROM Table2
WHERE outdated = 1;

或者您可以撤销订单,然后根本不需要检查b.outdated

DELETE FROM Table2
WHERE outdated = 1;

DELETE a
FROM Table1 AS a
LEFT JOIN Table2 AS b ON a.id_1 = b.id_1
WHERE b.id_1 IS NULL;