在mysql表中定位和删除元素

时间:2018-01-06 21:35:26

标签: mysql

我在一个名为ELEM的表中有一个包含数万个元素的数据库,我想删除其中一些元素。

我无法使用简单的命令(DELETE .. FROM ... WHERE ...),因为无法直接定位它们。

select * from ELEM;

+----+--------+
| id |  text  |
+----+--------+
|  1 | text1  |
|  2 | text2  |

但我可以找到他们的身份:

select * from connect where list_id=3

+-----+-----------+-----------+-----------+
| id  |  list_id  | elem_1_id | elem_2_id |
+-----+-----------+-----------+-----------+
| 378 |         3 |      2568 |      2569 |
| 379 |         3 |      2568 |      2570 |
| 380 |         3 |      2571 |      2572 |

如何使用此结果中的变量elem_1_idelem_2_idELEM表中删除?

2 个答案:

答案 0 :(得分:2)

假设您要从“ELEM”中删除'基于' connect'中的elem_1_id的表格你可以使用表格' IN'子查询:

DELETE FROM ELEM WHERE id IN (
  SELECT elem_1_id FROM connect WHERE list_id = 3
)

如果你想根据elem_1_id或elem_2_id删除,你可以做两个子查询,例如:

DELETE FROM ELEM WHERE id IN (
  SELECT elem_1_id FROM connect WHERE list_id = 3
) OR id IN (
  SELECT elem_2_id FROM connect WHERE list_id = 3
)

答案 1 :(得分:0)

我做这样的事情:

delete e.* from elem as e
inner join connect as c on c.elem_1_id = e.id
where c.list_id = 3;

delete e.* from elem as e
inner join connect as c on c.elem_2_id = e.id
where c.list_id = 3;