为帖子作者命名FK

时间:2017-03-29 12:14:58

标签: sql sql-server tsql

我有以下表格

create table dbo.Users (
  UserId int identity not null,
  Name nvarchar (400) not null
)

create table dbo.Posts (
  PostId int identity not null,
  UserId int not null,
  Title nvarchar (400) not null,
  Content nvarchar (max) not null,
)

On table Posts UserId是帖子的作者,它是Users.UserId PK的FK。

在这种情况下,我应该将UserId列命名为明确的关系是什么,或者AuthorId描述的是该帖子吗?

此命名最常用的方法是什么?

3 个答案:

答案 0 :(得分:5)

通常,我尝试使用与主键相同的名称来命名外键关系。所以我会用:

create table dbo.Posts (
    PostId int identity not null,
    UserId int not null,  -- this is the author of the post
    Title nvarchar(400) not null,
    Content nvarchar(max) not null,
    constraint fk_posts_userid foreign key (UserId) references Users(UserId)
);

我发现这使得很多更容易编写查询并跟踪已编写的查询。这在支持ANSI标准USING语法的数据库中也很实用。

一个例外是当对同一个引用表有多个引用时。然后我尝试在列名中包含主键名称:

create table dbo.Posts (
    PostId int identity not null,
    Author_UserId int not null,  -- this is the author of the post
    Approver_UserId int not null,
    Title nvarchar(400) not null,
    Content nvarchar(max) not null,
    constraint fk_posts_authoruserid foreign key (Author_UserId) references Users(UserId),
    constraint fk_posts_approveruserid foreign key (Approver_UserId) references Users(UserId)
);

不可否认,这不是命名的唯一方式,所以答案是(知情的)意见问题。例如,许多数据库命名idid,因此您无法遵循此约定。

答案 1 :(得分:3)

我总是使用外键名称中的表名,外键字段的名称通常与引用表中的名称相同。

在这个例子中

create table dbo.Users (
  UserId int identity not null,
  Name nvarchar (400) not null,

  constraint PK_UserId primary key (UserId)
)

create table dbo.Posts (
  PostId int identity not null,
  UserId int not null,
  Title nvarchar (400) not null,
  Content nvarchar (max) not null,

  constraint PK_PostId primary key (PostId),
  constraint FK_Posts_Users foreign key (UserId) references Users (UserId)
)

答案 2 :(得分:1)

有多个合理的命名标准,但我喜欢的关键是:

主键是实体名称,后跟_ID(或Id,如果您在展示时使用驼峰式广告,但我通常不会&#39 ;在SQL中)。

Foregin Key 是引用的实体名称,后跟_ID(或Id blah blah);如果需要,可选择在角色标识符前面加上。

所以UserId(虽然我拼写USER_ID)很好;或AuthorUserId。我不喜欢AuthorId,因为没有AUTHOR表。

它只是一层清晰度。理想情况下,您在数据字典中有描述,当然有人可以查看实际的FK约束(假设您使用实际的FK约束),但有一些约定让人们一眼就知道发生了什么更好

......一个小小的更新......

关于Gordon Linoff的非常相似的答案,我认为我唯一不同的是关于角色命名前缀的观点。当然有多个FK指向同一个表是最常见的情况,其中角色命名是绝对必要的,但我主张在任何时候关系含义都不清楚时使用它们。您的ORDER表只有帐单邮寄地址而不是送货地址或其他什么?很好,但我还是称之为' BILLING_ADDRESS_ID'

另外还有一个案例,其中基本上需要角色名称:自我引用。 EMPLOYEE_ID可以有MANAGER_EMPLOYEE_ID ...