开发者

Best datastructure for this relationship

I have a question about database 'style'.

I need a method of storing user accounts. Some users "own" other user accounts (sub-accounts). However not all user accounts are owned, just some.

Is it best to represent this using a table structure like so...

TABLE account开发者_C百科s (
 ID 
 ownerID -> ID
 name
)

...even though there will be some NULL values in the ownerID column for accounts that do not have an owner.

Or would it be stylistically preferable to have two tables, like so.

TABLE accounts (
 ID 
 name
)

TABLE ownedAccounts (
 accountID -> accounts(ID)
 ownerID -> accounts(ID)
)

Thanks for the advice.


I would keep the tables separate.

Self-referencing foreign keys can cause a lot of pain to update/delete.

With the combined table, a cascading delete on the owner will then delete all the owned accounts. (Which may or may not be desirable.) With the separate table, a cascade delete will only delete the relationship that the accounts were owned, and not the accounts themselves.


2nd choice is the best.

On a theoretical point of view, it is a regression of a 'n-to-m' (or 'many to many') relationship, where 'n' and 'm' side tables are merged in one unique 'Accounts' table, and where 'OwnedAccount' table is the linking table.

Using this model will allow you to implement data integrity rules at the server level without any problem. In addition to #mdma arguments, it will also make querying and reporting a lot easier. Further 'extensions' of ownership rules (multiple owners for one account, cascading ownership) could also be implemented in this model.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜