Is it possible to have a table with circular referential integrity keys to itself? In example, if I had a table called Container
ObjectId ParentId
1 1
2 1
3 2
ObjectId 1 references itself. Id’s 2 and 3 reference their respective parents, which are also in the same table. It wouldn’t be possible to delete 3 without deleteing 2, 2 without deleting 1, and it would be impossible to delete 1.
I know I could accomplish the same thing by having a cross reference table, such as,
ObjectId ContainerId
1 1
2 2
3 3
ContainerId ObjectId
1 1
2 1
3 3
But I’m interested in the first way of accomplishing it more, as it would eliminate a possibly unnecessary table. Is this possible?
I have done this many times. But be aware if you really are managing hierachies of data, SQL isn’t good at tree-like queries. Some SQL vendors have SQL extensions to help with this that might be usable, but Joe Celko’s ‘Nested Sets’ is the cat’s meow for this. You’ll get lots of hits in a search.
Currently I use the nested-sets approach with a self-reference ‘parentID’ as a short-cut for the references:
The rest are nested-sets queries.