简体   繁体   中英

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?

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. 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. Currently, you can still have an entry in [Post] that doesn't have an entry in [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

Create a new table with the following fields.

Title ID (PK, FK – Title Table) Publisher_ID (PK, FK – Pub table) Valid - bit Status (Unlimited)

After the fact:

alter table PostDetail
    add constraint FK_PostDetail_Post 
        foreign key (PostID) references Post (PostID)

Or in the table 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM