MySQL:如果条件存在于其他表中,则删除行

时间:2015-03-26 08:35:10

标签: mysql

我需要从'old_battles'表中删除行,如果它存在于'battles'表中且条件为:

如果'old_battles'中存在'battles'并且'old_battles.status =“已完成”'

,则删除该行

注意:old_battles.id = battles.id

表格结构: 战斗:

id     status
1     finished
2     cancelled
3     on progress
4     finished
5     finished

old_battles:

id     status
1     finished
2     cancelled
3     on progress
4     finished
5     finished

我的疑问:

delete from old_battles 
where old_battles.id in

(
select ob2.id
from old_battles ob2,battles b
where ob2.id = b.id
and ob2.status = 'finished'
)

1 个答案:

答案 0 :(得分:3)

考虑以下

mysql> create table battles (id int, status varchar(100));
Query OK, 0 rows affected (0.09 sec)

mysql> insert into battles values 
    -> (1,'finished'),
    -> (2,'cancelled'),
    -> (3,'on progress'),
    -> (4,'finished'),
    -> (5,'finished');
Query OK, 5 rows affected (0.03 sec)
Records: 5  Duplicates: 0  Warnings: 0

mysql> create table old_battles like battles;
Query OK, 0 rows affected (0.11 sec)

mysql> insert into old_battles values
    -> (1,'finished'),
    -> (2,'cancelled'),
    -> (3,'on progress'),
    -> (4,'finished'),
    -> (5,'finished');
Query OK, 5 rows affected (0.03 sec)
Records: 5  Duplicates: 0  Warnings: 0

以下是要删除的查询

delete ob from old_battles ob 
join battles b on b.id = ob.id where ob.status = 'finished';


mysql> select * from old_battles ;
+------+-------------+
| id   | status      |
+------+-------------+
|    2 | cancelled   |
|    3 | on progress |
+------+-------------+
2 rows in set (0.00 sec)