简体   繁体   中英

How to delete tree structure in sql?

I have a problem if I delete the first row id, then the parent_id won't delete in the table.

This is my example table structure, table name as 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

For example Case 1 :

If I delete Tom , the following the parent_id will together delete. That means all data will clear.

For example Case 2 :

If I delete Shawn , the following the parent_id will together delete. That means just left Tom in the table

For example Case 3 :

If I delete Jack , Jack, Howard and Owen will be delete.

For example Case 4 :

If I delete John , just John will be delete.

My tree structure will be like below the picture:

输出 1

Hope anyone can guide me or give me idea how to do. I try to find the findNextChildId to test, it can' work, maybe I don't know how to use it. Thanks.

You can use the foreign key constraint with the cascade referential action from the on delete subclause. To do this, I changed the definition of the column parent_id of the table table_1 . Since you have not determined which DBMS is used, I use 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM