我有一个名为music的数据库,里面有4个表;
我想删除数据库中与cd005(即cd_id列条目)相关的所有信息。
我想我可以使用
DELETE FROM table_name WHERE cd_id='cd005'
在每个单独的表上,但我想知道是否有办法通过立即从整个数据库中删除与此id相关的数据来解决此问题。
答案 0 :(得分: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