【问题标题】:How to delete tree structure in sql?如何删除sql中的树结构?
【发布时间】:2020-07-06 16:52:05
【问题描述】:

如果我删除第一行id有问题,那么parent_id不会在表中删除。

这是我的示例表结构,表名为 table_1

----------------------
id | name  | parent_id
----------------------
1    Tom       0
5    Shawn     1
11   Jack      5
13   John      5
20   David     5
33   Howard    11
35   Owen      33

例如Case 1:

如果我删除Tom,下面的parent_id 会一起删除。这意味着所有数据都将被清除。

例如Case 2:

如果我删除Shawn,下面的parent_id会一起删除。这意味着把 Tom 留在桌子上

例如Case 3:

如果我删除杰克,杰克、霍华德和欧文将被删除。

例如Case 4:

如果我删除 John,只会删除 John

我的树形结构如下图所示:

希望任何人都可以指导我或告诉我该怎么做。我试图找到 findNextChildId 进行测试,它不能工作,也许我不知道如何使用它。谢谢。

【问题讨论】:

  • 父母/孩子有多少级?

标签: sql treeview


【解决方案1】:

您可以将foreign key 约束与on delete 子条款中的cascade 引用操作一起使用。为此,我更改了表 table_1 的列parent_id 的定义。由于您尚未确定使用哪个 DBMS,我使用 MySQL v5.5。

create table table_1(
  id integer not null primary key,
  name varchar(15),
  parent_id integer null default null,
  foreign key(parent_id)
    references table_1(id)
    on delete cascade
);

insert into table_1(id, name, parent_id) values
  (1, 'Tom', null),
  (5, 'Shawn', 1),
  (11, 'Jack', 5),
  (13, 'John', 5),
  (20, 'David', 5),
  (33, 'Howard', 11),
  (35, 'Owen', 33);

create table names(name varchar(15));

insert into names(name) values ('Tom'), ('Shawn'), ('Jack'), ('John');

delimiter $$
create procedure test() begin
  declare v_name varchar(15);
  declare fetched int default true;
  declare c cursor for select name from names;
  declare continue handler for not found set fetched = false;
  open c;
  fetch c into v_name;
  while fetched do
    select v_name;
    start transaction;
      delete from table_1 where name = v_name;
      select * from table_1;
    rollback;
    fetch c into v_name;
  end while;
  close c;
end$$
delimiter ;

select * from table_1;
call test();

Demo.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 1970-01-01
    • 2012-03-05
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多