I’m building a database table representing a ‘note’ that has a parent-child relationship in two of it’s columns, like so:
ID INT(10) PK NOT NULL UNSIGNED ZEROFILL AUTOINCREMENT -- Primary key
parent_ID INT(10) UNSIGNED ZEROFILL -- References Primary key
username VARCHAR(30) NOT NULL
information VARCHAR(256) NOT NULL
comment VARCHAR(256) NOT NULL
where username is a foreign key to a user table and is the username of the person who wrote the note, information is the information contained in the note and comment is what username added. comment will always have something in it, and is not necessarily the same as the previous user.
The concept is that someone can “copy” a note and have their own comments, and say “I got this note from xxx”, hence the parent-child relationship. A bit like sharing in facebook, perhaps.
How do I correctly form the parent_ID column? Should I use an identifying relationship; which sides are mandatory?
I figure this has to be a 1-to-Many relationship since five people can copy the same note.
I expect there to be more copying than creating new notes, so there will be a relatively small number of NULL‘s in the records, but to get rid of nulls entirely should I apply a NOT NULL constraint and simply make the default parent 0 with an essentially meaningless record at ID 0 and take note of this in the software?
Is this even the correct way? Should I employ a two-table system with:
ID INT(10) PK
information VARCHAR(256)
orig_user VARHCAR(30) FK -- Potentially
and
ID INT(10) PK FK
username VARCHAR(30) PK FK
comment VARCHAR(256)
Which eliminates any possible NULL‘s by definiton?
Thanks
No, only
IDshould be in PK since it alone is unique. Also, a root (parent-less) note will have a NULLparent_IDand NULLs cannot be in PK.Correct. It’s also a tree, since there can be multiple levels of copying.
No need, FK would still be enforced on 0 and you’d need a “dummy” row just to satisfy it, as you already noted. FK ignores NULLs, so just put a NULL in the root note’s
parent_ID.This doesn’t model the same thing. It just allows you to connect to the original user, but not original note.
A different two-table design would be viable if a single note could have multiple parents, but that doesn’t seem to be the case here.
You seem very intent on eliminating NULLs. Any reason for that?
All in all, you should store notes in just one table, like this: