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

Mis*_*oul 1 mysql sql

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

例:

表格1

+--------+--------+
|   ID   | Author |
+--------+--------+
|  121   |  John  |
+--------+--------+
|  150   |  Ann   |
+--------+--------+
Run Code Online (Sandbox Code Playgroud)

表2

+--------+---------+-----------+
|   ID   | MetaKey | MetaValue |
+--------+---------+-----------+
|  121   |  Color  |    red    |
+--------+---------+-----------+
|  150   |  Color  |    grey   |
+--------+---------+-----------+
|  121   |  Weight |    10     |
+--------+---------+-----------+
|  150   |  Weight |    30     |
+--------+---------+-----------+
Run Code Online (Sandbox Code Playgroud)

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

Gor*_*off 5

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

delete from t2
where exists (select 1 from t1 where t2.id = t1.id and t1.Author = 'John')
Run Code Online (Sandbox Code Playgroud)

  • @MushinNoShin...如果你有一个关于`t1(id,Author)`的索引,那么两者都应该执行相同的操作.如果`t1`对于给定的`id`有多个匹配,那么`exists`应该表现得更好.这是标准的SQL.带有`join`语法的`delete`在所有数据库中都不可用. (2认同)