SQL relationships and best practices

孤街浪徒 提交于 2019-12-11 19:07:23

问题


If I have a User table and a Roles table.

What is the usual practice/pattern for adding the relationship?

Do I create an extra column in the User table for the RoleID or do people usually create a Relationships table like so:

Relationships Table

RelationshipID | UserID | RoleID |... any other relations a user might have

for the last bit, as a user you might create an endless amount of different types of things that all need to be related to you... do you instead add the relationship to each individual table created for each individual thing.. for example:

Pages Table

PageID | Title | Content | Author (UserID)

and so another table would also be similar to this:

Comments Table

CommentID | Comment | Author (UserID)

In this case, I would need to expand upon the Relationships table if I were to do it that way:

Relationships Table

RelationshipID | UserID | RoleID | CommentID

and i'd probably only want to fill in the UserID and CommentID as this relationship is not for the Roles... that is governed by another entry. so for example the values might be put in for a comment relationship:

AUTO           | 2      | NULL   | 16

I could imagine a multi purpose Revisions table being handy...

Revisions Table

RevisionID | DateCreated | UserID | ActionTypeID | ModelTypeID | Status | RelatedItemID
---------------------------------------------------------------------------------------
1          | <Now>       | 3      | 4 (Delete)   | 6 (Page)    | TRUE   | 38
2          | <Now>       | 3      | 1 (Delete)   | 5 (Comment) | TRUE   | 10
3          | <Now>       | 3      | 1 (Add)      | 5 (Comment) | FALSE  | 10

but not for a general Relationships table...

Does this sound correct?


Edit since comments: They stated that the relationships table should be made due to the many-to-many (data model)


So let's take my previous example of my possible relationship table:

Relationships Table Old

RelationshipID | UserID | RoleID | CommentID... etc

Should it actually be something more like this:

Relationships Table New

RelationshipID | ItemID        | LinkID     | ItemType    | LinkType | Status
---------------------------------------------------------------------------------
1              | 23(PageID)    | 7(UserID)  | ("Page")    | ("User") | TRUE
2              | 22(CommentID) | 7(UserID)  | ("Comment") | ("User") | TRUE
3              | 22(CommentID) | 23(PageID) | ("Comment") | ("Page") | TRUE

来源:https://stackoverflow.com/questions/20634016/sql-relationships-and-best-practices

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!