根据另一个表中的信息删除一个表中的行

时间:2013-08-29 13:16:56

标签: mysql sql

我想从Table2中删除我的行,其中ID存在于Table1中,而Table1中的值确定是否应该发生删除。

示例:

表1

+--------+--------+
|   ID   | Author |
+--------+--------+
|  121   |  John  |
+--------+--------+
|  150   |  Ann   |
+--------+--------+

表2

+--------+---------+-----------+
|   ID   | MetaKey | MetaValue |
+--------+---------+-----------+
|  121   |  Color  |    red    |
+--------+---------+-----------+
|  150   |  Color  |    grey   |
+--------+---------+-----------+
|  121   |  Weight |    10     |
+--------+---------+-----------+
|  150   |  Weight |    30     |
+--------+---------+-----------+

并删除Table2中的行,其中作者是'John'(来自表1)

2 个答案:

答案 0 :(得分:5)

您可以使用exists子句和相关子查询执行此操作:

delete from t2
where exists (select 1 from t1 where t2.id = t1.id and t1.Author = 'John')

答案 1 :(得分:3)

delete table2
from table2
inner join table1 on table1.ID = table2.ID
where table1.author = 'John'