mysql根据另一个表中的值删除行

时间:2017-10-27 10:06:45

标签: php mysql

我有一个表格,我希望删除INNER JOIN的行,其中WHERE子句基于另一个表中的值。表2中的primary_key是表1中的foreign_key

表1

table_1_id  |  customer_id  |  table_2_id
-----------------------------------------
     1      |      5        |       1 
     2      |      5        |       2 
     3      |      5        |       3 

表2

table_2_id   |    value
-----------------------
   1         |      0 
   2         |      0 
   3         |      1 

我想从表1中删除表2中value等于0的行。因此,在此示例中,DELETE语句应删除表1中的前两行,因为我使用INNER JOIN来连接这两个表。

我尝试了这个,但它并没有完全符合我的要求。此语句始终删除表1中的所有行,而不是仅删除前两行。

DELETE t1
FROM Table1 t1
INNER JOIN Table2 t2 ON (t1.table_2_id = t2.table_2_id) 
WHERE t1.customer_id = '5' 
AND t2.value = '0'

2 个答案:

答案 0 :(得分:3)

你的想法太复杂了。您想要从符合条件的表1中删除:

delete from t1 where customer_id = 5 and t2_id in (select t2_id from t2 where value = 0);

答案 1 :(得分:0)

我无法复制这种行为:

DROP TABLE IF EXISTS table1;

CREATE TABLE table1
(table_1_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,customer_id INT NOT NULL
,table_2_id INT NOT NULL
);

INSERT INTO table1 VALUES
(1,5,1),
(2,5,2),
(3,5,3);

DROP TABLE IF EXISTS table2;

CREATE TABLE table2
(table_2_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,value TINYINT NOT NULL
);

INSERT INTO table2 VALUES
(1,0),
(2,0),
(3,1);

SELECT * FROM table1;
+------------+-------------+------------+
| table_1_id | customer_id | table_2_id |
+------------+-------------+------------+
|          1 |           5 |          1 |
|          2 |           5 |          2 |
|          3 |           5 |          3 |
+------------+-------------+------------+
3 rows in set (0.01 sec)

SELECT * FROM table2;
+------------+-------+
| table_2_id | value |
+------------+-------+
|          1 |     0 |
|          2 |     0 |
|          3 |     1 |
+------------+-------+
3 rows in set (0.00 sec)

DELETE t1
FROM Table1 t1
INNER JOIN Table2 t2 ON t1.table_2_id = t2.table_2_id
WHERE t1.customer_id = 5
AND t2.value = 0
;

SELECT * FROM table1;
+------------+-------------+------------+
| table_1_id | customer_id | table_2_id |
+------------+-------------+------------+
|          3 |           5 |          3 |
+------------+-------------+------------+
1 row in set (0.00 sec)

请参阅。工作得很好。