如何在2列PK上设置不同表中的2个不同FK

时间:2013-08-13 05:36:42

标签: sql

我有3张桌子:

create table book (book_id int not null primary key, 
                   book_name char (100) unique) 

create table author (author_id int not null primary key,
                     authorname char (100) unique) 

create table bookauthor (book_id int, 
                         author_id int, 
                         CONSTRAINT pk_book_id PRIMARY KEY (book_id,author_id)) 

我想设置

  • book.book_id为fk到bookauthor.book_id
  • author.author_id为fk到bookauthor.author_id

请记住bookauthor中的pk在book_id,author_id上。

1 个答案:

答案 0 :(得分:1)

将您的bookauther表更改为

create table bookauther (
    book_id int , 
    auther_id int, 
    CONSTRAINT pk_book_id PRIMARY KEY (book_id,auther_id),
    FOREIGN KEY (book_id) REFERENCES book(book_id),
    FOREIGN KEY (auther_id) REFERENCES auther(auther_id)

)

查看FOREIGN KEY ConstraintsSQL FOREIGN KEY Constraint