从表中删除记录,如果其特定值未出现在另一个表中

时间:2013-12-11 12:55:14

标签: mysql sql join sql-delete notin

我有两张桌子。 T1t1field1t1field2T2t2field1t2field2。 如果T2

中不存在t2field1值,我想从t1field1删除所有记录
+----------+----------+
| t1field1 | t1field2 |
+----------+----------+
|   1      |    x     |
|   5      |    y     |
|   6      |    z     |
+----------+----------+

+----------+----------+
| t2field1 | t2field2 |
+----------+----------+
|   3      |    x     |
|   4      |    y     |
|   5      |    z     |
+----------+----------+

3 个答案:

答案 0 :(得分:3)

试试这个:

DELETE t2
FROM t2 LEFT JOIN t1 ON t1.t1field1 = t2.t2field1
WHERE t1.t1field1 IS NULL

DELETE FROM t2 WHERE t2.t2field1 NOT IN (SELECT t1.t1field1 FROM t1)

答案 1 :(得分:1)

delete t2
from t2
left join t1 on t1.t1field1 = t2.field1
where t1.field1 is null

答案 2 :(得分:1)

试试这个

  DELETE FROM T2 
  WHERE t2field1 NOT IN (SELECT t1field1 FROM T1)