[英]What is the SQL to create a table where its PK is also a FK?
Say I have: 说我有:
create table Post(
PostID int not null constraint PK_Post primary key clustered,
Title nvarchar(200) not null
) on [primary]
create table PostDetail(
PostID int not null constraint PK_PostDetail primary key clustered,
Text nvarchar(max) null
) on [primary]
How do I make PostDetail.PostID an FK referencing Post.PostID? 如何使PostDetail.PostID成为引用Post.PostID的FK?
Use: 采用:
ALTER TABLE POSTDETAIL
ADD CONSTRAINT fk_post
FOREIGN KEY (postid) REFERENCES POST (postid)
Though I have to say that what you've listed looks to be a one-to-one relationship - only one POSTDETAIL
record associates with a POST
record. 尽管我不得不说您列出的内容似乎是一对一的关系-只有一个
POSTDETAIL
记录与POST
记录相关联。 You might as well use: 您最好使用:
create table Post(
PostID int not null constraint PK_Post primary key clustered,
Title nvarchar(200) not null,
Text nvarchar(max) null
) on [primary]
If you want to make a proper 1-1 relationship, that's harder. 如果您想建立适当的1-1关系,那就很难了。 Currently, you can still have an entry in [Post] that doesn't have an entry in [PostDetail].
当前,您仍然可以在[Post]中有一个条目,而在[PostDetail]中没有条目。
If you want to go one step further, you may want to research Tony Rogerson's recent investigations into the problem, at http://sqlblogcasts.com/blogs/tonyrogerson/archive/2010/01/23/how-to-create-a-one-to-one-relationship-in-sql-server-using-dri-triggers-and-views.aspx 如果您想更进一步,则可能要研究托尼·罗杰森(Tony Rogerson)最近对该问题的调查, 网址为http://sqlblogcasts.com/blogs/tonyrogerson/archive/2010/01/23/how-to-create-a使用dri-triggers-and-views.aspx在SQL Server中建立一对一关系
Create a new table with the following fields. 使用以下字段创建一个新表。
Title ID (PK, FK – Title Table) Publisher_ID (PK, FK – Pub table) Valid - bit Status (Unlimited) 标题ID(PK,FK –标题表)Publisher_ID(PK,FK –发布表)有效-位状态(无限制)
After the fact: 事实之后:
alter table PostDetail
add constraint FK_PostDetail_Post
foreign key (PostID) references Post (PostID)
Or in the table def: 或在表def中:
create table PostDetail(
PostID int not null constraint PK_PostDetail primary key clustered,
Text nvarchar(max) null,
constraint FK_PostDetail_Post foreign key (PostID) references Post (PostID)
) on [primary]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.