无法添加外键SQL小提琴

时间:2017-03-26 21:08:49

标签: sql fiddle

我是sql的新手,我在我的表中遇到了外键问题。如果有任何可以指出错误,请做,我不知道它是什么。enter image description here

CREATE TABLE donut(
  donutId int(5) NOT NULL, 
  name VARCHAR(20), 
  descriptioin VARCHAR(60), 
  price DECIMAL(8,3), 
  PRIMARY KEY (donutId) 
);

CREATE TABLE customer(
customerid INT(5)NOT NULL,
firstname VARCHAR(30),
lastname VARCHAR(30), 
addres VARCHAR(100),
apt VARCHAR(20),
city VARCHAR(30),
state VARCHAR(20),    
zip VARCHAR(8),
homephone  VARCHAR(15),          
cellphone  VARCHAR(15),
otherphone VARCHAR(15),
PRIMARY KEY (customerid) );

CREATE TABLE customer_order_donut(
orderid int(10) NOT NULL,
customerid int(10),
donutId int(10), 
orderdate datetime,
donutqty INT(5),
specialhandling TEXT,
PRIMARY KEY (orderid) 
customerid int FOREIGN KEY REFERENCES customer(customerid),
donutId int FOREIGN KEY REFERENCES donut(donutId));

2 个答案:

答案 0 :(得分:0)

检查syntax of the FOREIGN KEY约束(并在PRIMARY KEY之后添加逗号):

CREATE TABLE customer_order_donut(
orderid int(10) NOT NULL,
customerid int(10),
donutId int(10), 
orderdate datetime,
donutqty INT(5),
specialhandling TEXT,
PRIMARY KEY (orderid),
FOREIGN KEY (customerid) REFERENCES customer(customerid),
FOREIGN KEY (donutid) REFERENCES donut(donutId)
);

答案 1 :(得分:0)

您的FOREIGNKEY语法错误。这应该有效:

CREATE TABLE donut
(
  donutid      INT(5) NOT NULL,
  name         VARCHAR(20),
  descriptioin VARCHAR(60),
  price        DECIMAL(8,3),
  PRIMARY KEY (donutid)
);
CREATE TABLE customer
(
  customerid INT(5)NOT NULL,
  firstname  VARCHAR(30),
  lastname   VARCHAR(30),
  addres     VARCHAR(100),
  apt        VARCHAR(20),
  city       VARCHAR(30),
  state      VARCHAR(20),
  zip        VARCHAR(8),
  homephone  VARCHAR(15),
  cellphone  VARCHAR(15),
  otherphone VARCHAR(15),
  PRIMARY KEY (customerid)
);
CREATE TABLE customer_order_donut
(
  orderid    INT(10) NOT NULL,
  customerid INT(10),
  donutid    INT(10),
  orderdate  DATETIME,
  donutqty   INT(5),
  specialhandling TEXT,
  PRIMARY KEY (orderid),
  FOREIGN KEY (customerid) REFERENCES customer(customerid),
  FOREIGN KEY (donutid) REFERENCES donut(donutid)
);