主外键

--主表
CREATE TABLE AUTHOR
(
  AUTHOR_ID int NOT NULL ,
  AUTHOR_NAME VARCHAR(100)
)

--子表/从表
CREATE TABLE BOOK
(
  BOOK_ID int  NOT NULL,
  BOOK_NAME VARCHAR(100),
  AUTHOR_ID int NOT NULL
)

个人认为:

外键是约束的一种。不存在主从关系,只存在引用关系,如部门表与员工表。每个员工都属于某个部门,必须与某个部门资料对应。

主从表的情况:类似于订单表与订单明细表的关系。

希望以上有所帮助.

alter table AUTHOR add constraint PK_OF_AUTHOR primary key (AUTHOR_ID)
alter table BOOK add constraint PK_OF_BOOK primary key (BOOK_ID)
alter table BOOK add constraint FK1
foreign key (AUTHOR_ID) references AUTHOR(AUTHOR_ID)

insert into author(AUTHOR_ID,AUTHOR_NAME) values(1,'author1')
insert into author(AUTHOR_ID,AUTHOR_NAME) values(2,'author2')

insert into book(BOOK_ID,BOOK_NAME,AUTHOR_ID) values(1,'book1',1)
insert into book(BOOK_ID,BOOK_NAME,AUTHOR_ID) values(2,'book2',2)

DELETE FROM BOOK WHERE AUTHOR_ID=1
DELETE FROM AUTHOR WHERE AUTHOR_ID=1

posted on 2009-11-09 11:06  highmayor  阅读(214)  评论(0编辑  收藏  举报

导航