no, you can have a root node. just set it's parent id to NULL instead of 0. then you can use foreign keys to restrict the ability to delete rows that still have children.
here's a representation of your future family tree that demonstrates this:
Code:
mysql> create table jake (
id int auto_increment primary key
, parent int
, name varchar(10)
, index(parent)
, constraint foreign key (parent) references jake(id) on delete restrict
) engine = innodb;
Query OK, 0 rows affected (0.14 sec)
mysql> insert jake (name, parent)
values
('jake', null)
, ('jake jr', 1)
, ('jackie', 1)
, ('jake iii', 2);
Query OK, 4 rows affected (0.03 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> select * from jake;
+----+--------+----------+
| id | parent | name |
+----+--------+----------+
| 1 | NULL | jake |
| 2 | 1 | jake jr |
| 3 | 1 | jackie |
| 4 | 2 | jake iii |
+----+--------+----------+
3 rows in set (0.00 sec)
so you have 2 children, jake jr and jackie. jake jr has a child name jake iii.
notice how i can't delete you:
Code:
mysql> delete from jake where name = 'jake';
ERROR 1451 (23000): Cannot delete or update a parent row:
a foreign key constraint fails
(`test/jake`, CONSTRAINT `jake_ibfk_1` FOREIGN KEY (`parent`) REFERENCES `jake` (`id`))
and i also can't delete jake jr until i delete your grandson:
Code:
mysql> delete from jake where name = 'jake jr';
ERROR 1451 (23000): Cannot delete or update a parent row:
a foreign key constraint fails
(`test/jake`, CONSTRAINT `jake_ibfk_1` FOREIGN KEY (`parent`) REFERENCES `jake` (`id`))
mysql> delete from jake where name = 'jake iii';
Query OK, 1 row affected (0.02 sec)
mysql> delete from jake where name = 'jake jr';
Query OK, 1 row affected (0.02 sec)
and i still can't delete you because you still have a daughter:
Code:
mysql> delete from jake where name = 'jake';
ERROR 1451 (23000): Cannot delete or update a parent row:
a foreign key constraint fails
(`test/jake`, CONSTRAINT `jake_ibfk_1` FOREIGN KEY (`parent`) REFERENCES `jake` (`id`))
and finally, notice that i can't add jake iii back because his father doesn't exist:
Code:
mysql> insert jake (name, parent) values ('jake iii', 2);
ERROR 1452 (23000): Cannot add or update a child row:
a foreign key constraint fails
(`test/jake`, CONSTRAINT `jake_ibfk_1` FOREIGN KEY (`parent`) REFERENCES `jake` (`id`))
but i can add him as a his own "root" node:
Code:
mysql> insert jake (name, parent) values ('jake iii', NULL);
Query OK, 1 row affected (0.01 sec)
oh, and make sure you're using innodb tables because myisam does not (yet) support them.
Bookmarks