开发者

Enforce an entity to only exist as a parent OR child in a relationship table

Edit: Apologies, I have now reworded my question as my colleague and I were in a rush when it was initially written and I noticed it was badly phrased.

I have a contact table as follows:

Contact

Contact id

some more fields

A contact must either be a child or a parent. I have a parent child relationship table:

Parent Children

id

Parent id

Child id

You cannot have a tree depth of greater than one within this table (I already know how to do this bit). The part I am unsure about is that I want to make sure when adding to the 'parent children' table that parents and children cannot be added to the wrong column - ie a parent can only go to the parent column, and a child can only go to the child column.

Contacts are currently defined to be a parent or a child with a flag in the contact table which I do not think is the best system. This is because it 开发者_StackOverflowis possible for a parent to have no children, or child to have no parents hence no presence of the contact in 'Parent Children'

So in summary I want to store contacts which must be either a parent or child. They do not have be part of any relationship, but if they are they will be stored as parent child relationships which can only have a depth one (enforcing the tree depth is the part I currently know how to do), and I want to make sure a parent contact can only be a parent in the relationship table, and a child contact can only be a child in the relationship table.


you can simplify things (if you have a maximum depth of 1):

Table People

id | parent_id | name

Table Contact

id | people_id 

How it works:

A person out of the people table is a parent if parent_id IS NULL.

Select all children:

SELECT * FROM people WHERE parent_id IS NOT NULL

Select all parents:

SELECT * FROM people WHERE parent_id IS NULL

Select all parent contacts:

SELECT * FROM contacts
   INNER JOIN people ON people.id = contacts.people_id 
WHERE
   people.parent_id IS NULL

Select all child contacts:

SELECT * FROM contacts
   INNER JOIN people ON people.id = contacts.people_id 
WHERE
   people.parent_id IS NOT NULL


I don't know if I have got your question but If you need a parent child relationship where the record is not "rich" you could keep everything in one table even to improve the performance

Contact
-IdContact
-IdParentContact  (will be an IdContact)
-OtherFields

all the root will have ParentContact at NULL

Do am I missing something?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜