【问题标题】:Cascade Delete records in DB级联删除数据库中的记录
【发布时间】:2014-01-13 08:11:04
【问题描述】:

我有父子关系表:

id   text        parent_id
1   'test'       0
2   'test1'      1
3   'test2'      2
4   'test3'      0

我有一个像这样构建树的函数:

test
  - test1
    -- test2
test3

比如我想删除test1,但是我需要删除他所有的child,我该怎么做,或者我需要使用什么技术?

我尝试在同一张表上添加外键,但不起作用

【问题讨论】:

  • 你可以通过一些代码逻辑或多个sql查询来做到这一点。

标签: php sql recursion


【解决方案1】:

像这样添加约束

ALTER TABLE 
    `table` 
ADD FOREIGN KEY 
    (`parent_id`) 
REFERENCES 
    `table` (`id`) 
ON UPDATE CASCADE 
ON DELETE CASCADE;

重要提示:您的表必须是 InnoDB

【讨论】:

  • 当我尝试改变我的表时,我有一个错误:(errno: 150) 外键约束的格式不正确 */ 我的查询: ALTER TABLE my_table ADD CONSTRAINT FK_relations FOREIGN KEY ( id) 参考my_table (parent_id) 删除级联;
  • 之前截断你的表,如果不可能的话,显示你的表 DDL
  • rh_ipv6 |创建表rh_ipv6 (id int(11) NOT NULL AUTO_INCREMENT, address varchar(64) NOT NULL, type int(1) DEFAULT '0', node int(11) DEFAULT NULL, @ 987654332@ int(1) DEFAULT '0', mask int(3) NOT NULL, product varchar(15) NOT NULL, subnets varchar(100) NOT NULL, therange varchar(100) NOT NULL , group int(5) 默认 '0', id_service int(11) NOT NULL, status varchar(100) NOT NULL, start varchar(50) 默认 NULL, end varchar(50)默认 NULL,parent_id int(11) NOT NULL 默认 '0',主键 (id)) ENGINE=InnoDB AUTO_INCREMENT=3 默认 CHARSET=utf8 |
  • parent_id 不能为0,应该和id值明确匹配
  • 0 表示这条记录是树根,你可以在我的例子中看到它
猜你喜欢
  • 2016-11-05
  • 1970-01-01
  • 2019-06-03
  • 2011-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多