繁体   English   中英

SQL删除基于另一个表的行

[英]SQL Delete Rows Based on Another Table

这可能很容易,但现在是星期一早上。 我有两个表:

表1:

Field        | Type             | Null | Key | Default | Extra
id           | int(32) unsigned | NO   | PRI | NULL    | auto_increment
group        | int(32)          | NO   |     | 0       |                

表2:

Field     | Type             | Null | Key | Default | Extra
group     | int(32)          | NO   |     | 0       | 

忽略其他字段...我想要一个 SQL DELETE 语句,该语句将删除 Table1 中存在等于 Table1.group 的 Table2.group 的所有行。 因此,如果 Table1 的一行具有 group=69,则当且仅当 Table2 中存在 group=69 的行时,才应删除该行。

感谢您的任何帮助。

我认为这就是你想要的:

DELETE FROM `table1`
WHERE `group` in (SELECT DISTINCT `group` FROM `table2`)

我认为这种方式更快:

DELETE FROM t1 USING table1 t1 INNER JOIN table2 t2 ON ( t1.group = t2.group );

好的解决方案就是按照您自己已经说过的方式编写 SQL:

DELETE FROM Table1
WHERE
  EXISTS(SELECT 1 FROM Table2 WHERE Table2.Group = Table1.Group)

问候, 阿诺·布林克曼

像这样的东西

delete from table1 where group in (select group from table2)

在我的头顶:

delete from Table1 where id in (select id from table1 inner join table2 on Table1.group = Table2.group)

我这样做与其他海报略有不同——我认为如果 Table2 上有大量行,这可能会更好。 有人可以让我直截了当吗?

您可以通过在简单的连接查询中使用其别名来删除任一表行,例如

delete a from table1 a,table2 b where a.uid=b.id and b.id=57;

在这里,您可以指定 a 或 b 来删除相应的表行

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM