学校的数据库实验课,遇到一个不能执行的sql



 sql


 DROP DATABASE IF EXISTS library; 

CREATE DATABASE library; 

USE library; 

CREATE TABLE title 
  ( 
     callnumber VARCHAR(40) NOT NULL, 
     name       VARCHAR(200), 
     isbn       VARCHAR(40) NOT NULL, 
     year       DATE, 
     publisher  VARCHAR(80), 
     PRIMARY KEY (callnumber), 
     UNIQUE(isbn) 
  ); 

CREATE TABLE member 
  ( 
     memno          INT UNSIGNED NOT NULL, 
     driverlicstate VARCHAR(20), 
     driverlicno    VARCHAR(40), 
     fname          VARCHAR(20), 
     mi             VARCHAR(10), 
     lname          VARCHAR(20), 
     address        VARCHAR(250), 
     phonenumber    VARCHAR(15), 
     PRIMARY KEY (memno) 
  ); 

CREATE TABLE book 
  ( 
     book_id       INT UNSIGNED NOT NULL, 
     edition       VARCHAR(80), 
     borrowermemno INT UNSIGNED, 
     borrowduedate DATE, 
     callnumber    VARCHAR(40), 
     libcheck      INT UNSIGNED, 
     PRIMARY KEY (book_id), 
     FOREIGN KEY (callnumber) REFERENCES title(callnumber), 
     FOREIGN KEY (borrowermemno) REFERENCES member(memno), 
     FOREIGN KEY (libcheck) REFERENCES librarian(ssn) 
  ); 

CREATE TABLE librarian 
  ( 
     ssn      INT UNSIGNED NOT NULL, 
     name     VARCHAR(80), 
     address  VARCHAR(250), 
     salary   NUMERIC(9, 2), 
     gender   CHAR(1), 
     birthday DATE, 
     superssn INT UNSIGNED, 
     section  INT UNSIGNED, 
     PRIMARY KEY (ssn) 
  );

就是这段sql,在执行的时候Book表是不能被创建的,因为他引用了Librarian的字段做外键,可是Librarian还没有被创建。如果调换顺序的话还是有问题(会有Librarian也引用了book表某个字段作为外键这种情况)。请问这样的sql怎么能执行呢??

sql 数据库 mysql

两弹元老黄仁勋 9 years, 7 months ago

首先你应该把你的需求说一下是什么?其次你的Librarian表引用Book表的哪个字段了?如果Librarian也用了Book表中的字段,说明你的ER图设计的有点问题。感觉你的表之间的关系藕合度太高了,建议重新设计下ER图较好。

不吸血滴蚊子 answered 9 years, 7 months ago

你为什么非得这么执行呢?

我们能不能先把表都建立好,然后再来确定主外键关系?

毁灭的私生女 answered 9 years, 7 months ago

Your Answer