Sql 为文章作者命名FK
我有下列表格Sql 为文章作者命名FK,sql,sql-server,tsql,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, ) 在
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,
)
在表Posts上,UserId是帖子的作者,它是一个FK to Users.UserId PK
在这种情况下,我应该给列命名为UserId,这清楚地表明了它与文章的关系,还是authord描述了它与文章的关系
最常用的命名方法是什么?通常,我会尝试使用与主键相同的名称命名外键关系。因此,我将使用:
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标准的数据库中也很实用
一个例外是,对同一个引用表有多个引用。然后我尝试在列名中包含主键名称:
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)
);
诚然,这不是唯一的命名方式,因此答案是(知情的)意见问题。例如,许多数据库将
id
列命名为id
,因此无法遵循此约定。有多种合理的命名标准,但我喜欢的密钥方案是:
主键是实体名称,后跟\u ID
(或者ID
,如果您使用的是驼峰大小写,如图所示,但在SQL中通常不使用驼峰大小写)
Foregin键是引用的实体名称,后跟\u ID
(或ID
等等);为清晰起见,如果需要,可选择在前面加上角色标识符
所以UserId
(尽管我会拼写它UserId
)很好;或AuthorUserId
。我不喜欢AuthorId
,因为没有AUTHOR
表
这只是一个清晰的层次。理想情况下,您应该在数据字典中有描述,当然有人可以查看实际的FK约束(假设您使用实际的FK约束),但是有一些约定可以让人一目了然地知道发生了什么更好
…一个小的更新
关于Gordon Linoff给出的非常相似的答案,我认为唯一不同的是关于角色命名前缀的问题。当然,有多个指向同一个表的FK是最常见的情况,其中角色命名是绝对必要的,但我主张在关系含义不明确的任何时候使用它们。您的订单
表中只有账单地址,而没有发货地址或其他什么?好吧,但我还是叫它“账单地址ID”
还有一种情况基本上需要角色名:自引用
EMPLOYEE_ID
可以有一个MANAGER\u EMPLOYEE_ID
..我总是在外键名称中使用表的名称,我通常命名的外键字段与引用表中的相同
在这个例子中,这将是
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)
)
这需要的是意见而不是事实。我会保留它的UserId,因为它对于您的数据库结构更加清晰和直观。当从用户中选择名称时,我会给它一个别名“Author”,仅此而已。这是基于非正常的观点。我总是使用这个表的名称和引用表的名称,在这个示例中,字段的名称是UserID,外键是FK_POSTS_USERS。@SqlZim。谢谢。无论如何,我同意戈登的惯例,只是我不在列名中使用下划线。