Remove records from table, if its specific value does not appears in another table

394 views Asked by At

I have two tables. T1 has t1field1 and t1field2, and T2 has t2field1 and t2field2. I want to remove all records from T2, if t2field1 value does not exist in t1field1

+----------+----------+
| t1field1 | t1field2 |
+----------+----------+
|   1      |    x     |
|   5      |    y     |
|   6      |    z     |
+----------+----------+

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

There are 3 answers

0
Saharsh Shah On BEST ANSWER

Try this:

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

OR

DELETE FROM t2 WHERE t2.t2field1 NOT IN (SELECT t1.t1field1 FROM t1)
0
juergen d On
delete t2
from t2
left join t1 on t1.t1field1 = t2.field1
where t1.field1 is null
0
uvais On

try this

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