从数据库中删除条目的所有信息(MySQL)

时间:2012-04-15 18:55:26

标签: mysql database sql-delete

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

  1. band_members
  2. 频带
  3. CDS
  4. 版本。
  5. 我想删除数据库中与cd005(即cd_id列条目)相关的所有信息。

    我想我可以使用

    DELETE FROM table_name WHERE cd_id='cd005'
    

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

1 个答案:

答案 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