删除查询 - mysql
Delete query - mysql
如果我有 table 例如:
name1 | name2 | id |
+----------------+--------------+-----------+
| A | E | 1 |
| A | F | 1 |
| B | G | 1 |
| C | H | 1 |
| D | I | 1 |
| A | J | 2 |
| B | K | 2 |
| C | L | 2 |
| D | M | 2 |
| A | N | 2 |
我需要的是删除所有包含 name2 = E 的 id 行
如果我这样做:
delete from table where name2 = E
它只给我这个
name1 | name2 | id |
+----------------+--------------+-----------+
| A | F | 1 |
| B | G | 1 |
| C | H | 1 |
| D | I | 1 |
| A | J | 2 |
| B | K | 2 |
| C | L | 2 |
| D | M | 2 |
| A | N | 2 |
我想要的结果是:
name1 | name2 | id |
+----------------+--------------+-----------+
| A | J | 2 |
| B | K | 2 |
| C | L | 2 |
| D | M | 2 |
| A | N | 2 |
我应该使用哪个查询?
我想你想要这样的东西:
delete t
from table t join
table t2
on t.id = t2.id and t2.name2 = 'E';
这会删除 table 中与 name2
为 'E'
的行共享同一 ID 的所有行。
在大多数其他数据库中,您可以这样写:
delete t from table t
where t.id in (select t2.id from table t2 where t2.name2 = 'E');
或使用 exists
的类似内容。不幸的是,MySQL 不允许这种语法,因为子查询引用了正在修改的 table。有一个黑客:
delete t from table t
where t.id in (select id from (select t2.id from table t2 where t2.name2 = 'E') t);
我更喜欢带有 join
的版本。
对于 select
,我会这样做:
select t.*
from table t
where t.id in (select t2.id from table t2 where t2.name2 = 'E');
或:
select t.*
from table t
where exists (select 1 from table t2 where t2.name2 = 'E' and t2.id = t.id);
如果我有 table 例如:
name1 | name2 | id |
+----------------+--------------+-----------+
| A | E | 1 |
| A | F | 1 |
| B | G | 1 |
| C | H | 1 |
| D | I | 1 |
| A | J | 2 |
| B | K | 2 |
| C | L | 2 |
| D | M | 2 |
| A | N | 2 |
我需要的是删除所有包含 name2 = E 的 id 行
如果我这样做:
delete from table where name2 = E
它只给我这个
name1 | name2 | id |
+----------------+--------------+-----------+
| A | F | 1 |
| B | G | 1 |
| C | H | 1 |
| D | I | 1 |
| A | J | 2 |
| B | K | 2 |
| C | L | 2 |
| D | M | 2 |
| A | N | 2 |
我想要的结果是:
name1 | name2 | id |
+----------------+--------------+-----------+
| A | J | 2 |
| B | K | 2 |
| C | L | 2 |
| D | M | 2 |
| A | N | 2 |
我应该使用哪个查询?
我想你想要这样的东西:
delete t
from table t join
table t2
on t.id = t2.id and t2.name2 = 'E';
这会删除 table 中与 name2
为 'E'
的行共享同一 ID 的所有行。
在大多数其他数据库中,您可以这样写:
delete t from table t
where t.id in (select t2.id from table t2 where t2.name2 = 'E');
或使用 exists
的类似内容。不幸的是,MySQL 不允许这种语法,因为子查询引用了正在修改的 table。有一个黑客:
delete t from table t
where t.id in (select id from (select t2.id from table t2 where t2.name2 = 'E') t);
我更喜欢带有 join
的版本。
对于 select
,我会这样做:
select t.*
from table t
where t.id in (select t2.id from table t2 where t2.name2 = 'E');
或:
select t.*
from table t
where exists (select 1 from table t2 where t2.name2 = 'E' and t2.id = t.id);