0

我有一个名为 music 的数据库,里面有 4 个表;

  1. 乐队成员
  2. 乐队
  3. 光盘
  4. 发布。

我想删除数据库中与 cd005 相关的所有信息(即 cd_id 列条目)。

我想我可以使用

DELETE FROM table_name WHERE cd_id='cd005'

在每个单独的表上,但我想知道是否有办法通过一次从整个数据库中删除与此 id 相关的数据来解决这个问题。

4

1 回答 1

1

是的,有办法。请检查 mysql 文档中的外键级联删除。

例子:

CREATE TABLE parent (id INT NOT NULL,
                     PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (id INT, parent_id INT,
                    INDEX par_ind (parent_id),
                    FOREIGN KEY (parent_id) REFERENCES parent(id)
                      ON DELETE CASCADE
) ENGINE=INNODB;

Insert into parent set id=1;
Insert into parent set id=2;
Insert into parent set id=3;
Insert into child set id=1, parent_id=1;
Insert into child set id=2, parent_id=1;


select * from parent;
select * from child;
delete from  parent where id=1;
select * from parent;
select * from child;


ID
1
2
3
 Record Count: 3; Execution Time: 0ms View Execution Plan
ID  PARENT_ID
1   1
2   1
 Record Count: 2; Execution Time: 0ms View Execution Plan
 Record Count: 0; Execution Time: 1ms
ID
2
3
 Record Count: 2; Execution Time: 0ms View Execution Plan
 Record Count: 0; Execution Time: 0ms
于 2012-04-15T19:02:03.083 回答