tags:

views:

51

answers:

1

I have a "categories" table that has a structure:

  • categoryId
  • parentId
  • categoryName

This table represents categorized tree structure where parentId is actually a pointer to categoryId.

Is it possible to put a foreign key RESTRICT to parentId which points to categoryId so that I disable deletion of children nodes?

+2  A: 

Yes, certainly a table may have a foreign key referencing itself. eg.:

CREATE TABLE categories (
    categoryId INTEGER NOT NULL PRIMARY KEY,
    parentId INTEGER REFERENCES categories(categoryId),
    categoryName VARCHAR(32) NOT NULL
);

Naturally you will need to be using InnoDB not MyISAM for this to do anything.

bobince
Thanks but now I have another problem, how do I enter the first record that should be: categoryId = 1, parentId = 0, categoryName = 'test', when there is no categoryId with 0 value.
dfilkovi
Use `NULL` rather than `0` for no parentId.
bobince
Yes NULL works but query is different then. I use a recursive function in php "WHERE parentId=$var" and if is null I need to use "WHERE parentId IS NULL" and that complicates things a lot.
dfilkovi
Unfortunately, that's the complication you need to deal with when using self-referencing foreign keys. Your PHP will need to be a little smarter to deal with the root node of the tree as a special case.
friedo
The other solutions are to give the root node itself as a parent, or to have a dummy node above the root node with ID 0. I would stick with the null though. If you're doing a lot of recursive queries for arbitrary-deptch hierarchies, the parent-reference is not a good model; you may want to look at an alternative such as nested sets. See http://dev.mysql.com/tech-resources/articles/hierarchical-data.html
bobince