SQL关系和最佳实践

时间:2013-12-17 12:22:36

标签: sql relationship

如果我有用户表和角色表。

添加关系的常用练习/模式是什么?

我是否在User表的RoleID中为RoleID创建了一个额外的列,或者人们通常会创建一个Relationships表,如下所示:

关系表

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

对于最后一点,作为用户,您可能会创建无数种不同类型的事物,这些事物都需要与您相关...您是否将关系添加到为每个事物创建的每个单独的表中。例如:

页面表

PageID | Title | Content | Author (UserID)

所以另一个表也类似于:

评论表

CommentID | Comment | Author (UserID)

在这种情况下,如果我这样做,我需要扩展Relationships表:

关系表

RelationshipID | UserID | RoleID | CommentID

我可能只想填写UserID和CommentID,因为这种关系不适用于由另一个条目管理的角色......例如,可以为评论关系输入值:

AUTO           | 2      | NULL   | 16

我可以想象一个多用途的Revisions表很方便......

修订表

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

但不适用于一般关系表......

这听起来不错吗?


自评论后修改 他们表示,关系表应该由多对多(数据模型)

组成

所以让我们先前举例说明我可能的关系表:

关系表旧

RelationshipID | UserID | RoleID | CommentID... etc

它应该更像这样:

关系表新

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

0 个答案:

没有答案
相关问题