Pergunta

I have a MySQL table like this:

CREATE TABLE categories
(
      ID INT NOT NULL,
      Name VARCHAR(100) NULL,
      Parent INT NULL,
      PRIMARY KEY (ID)
)Engine=InnoDB

What I'd like to do is ensure the deletion of all children whenever a parent gets deleted. At first, I wanted to do it by adding a foreign key like that to the table:

ALTER TABLE categories ADD CONSTRAINT FOREIGN KEY Parent(Parent) 
REFERENCES categories(ID) ON DELETE CASCADE

This doesn't work. I've also tried internal relations, but without success.

Parents and their children are linked with a recursive PHP function. Is there a way in MySQL to achieve the goal, or it should be done using PHP?

Foi útil?

Solução

Works for me.

#Server version: 5.1.42-community MySQL Community Server (GPL)
create table lists(
   id int not null
  ,parent int
  ,primary key(id)
  ,foreign key(parent) references lists(id) on delete cascade
) Engine=InnoDb;

insert into lists(id, parent) values(1, null);
insert into lists(id, parent) values(2, 1);
insert into lists(id, parent) values(3, 2);
insert into lists(id, parent) values(4, 3);

mysql> select * from lists;
+----+--------+
| id | parent |
+----+--------+
|  1 |   NULL |
|  2 |      1 |
|  3 |      2 |
|  4 |      3 |
+----+--------+
4 rows in set (0.00 sec)

mysql>
mysql> delete from lists where id = 1;
Query OK, 1 row affected (0.02 sec)

mysql>
mysql> select * from lists;
Empty set (0.00 sec)

Outras dicas

You have defined the Foreign Key the other way around.
You should Define it as:

ALTER TABLE categories ADD CONSTRAINT FOREIGN KEY (id)
REFERENCES Parent(Parent) ON DELETE CASCADE 

you need something like this:

drop table if exists categories;
create table categories
(
cat_id int unsigned not null auto_increment primary key,
name varchar(255) not null,
parent_id int unsigned null,
foreign key (parent_id) references categories(cat_id) on delete cascade
)
engine = innodb;

Ronnis, Foo, you're right. It really works. :-)

The thing I was doing wrong was putting "0" for the first parent via my PHP application. Of course, if I put "0" (there's no parent with the id "0"), then I'm violating the foreign key rules. So, all I had to do was to edit my INSERT statement a little bit. Thank you a lot for bringing this to my attention. Thanks everybody!

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top