SQL Fiddle - 无法添加外键约束

SQL Fiddle - cannot add foreign key constraint

我在为我的 salesorderslineitem table 构建模式时遇到问题。即使我尝试在 fiddle 中自行构建模式。我收到一条错误消息无法添加外键约束...在这里,我的 table 一起试图让新的销售订单项目 table 正常工作。谢谢大家!

CREATE TABLE salesorders
( donut_order_id             INT(10) NOT NULL AUTO_INCREMENT,
  customer_id                INT,
  date                       DATETIME,
  special_handling_note      TEXT,
  PRIMARY KEY (donut_order_id),
  FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);

INSERT INTO salesorders
 (donut_order_id,date,special_handling_note)

VALUES( 0000001,"2018-04-22","Please include plates and napkins");

CREATE TABLE salesorderslineitem
(
  donut_order_id     INT(10) NOT NULL, 
  donut_id           INT(10) NOT NULL,
  qty                INT(10) NOT NULL,
  PRIMARY KEY (donut_order_id, donut_id),
  FOREIGN KEY (donut_order_id) REFERENCES salesorders(donut_order_id),
  FOREIGN KEY (donut_id) REFERENCES donuts(donut_id)
 );

INSERT INTO salesorderslineitem
 (qty)

VALUES (10);

CREATE TABLE donuts
 (donut_id     INT(10) NOT NULL AUTO_INCREMENT,
  name         VARCHAR(30),
  description  VARCHAR(50),
  unit_price   DECIMAL(8,3),
  PRIMARY KEY (donut_id)
 );

INSERT INTO donuts
 (name,description,unit_price)

我已经解决了你所有的问题。

这是一个有效的 SQLFiddle。 http://sqlfiddle.com/#!9/5071d0

第一个问题是还没有为 Customers table 定义 CREATE Statement 并且正在尝试向这个不存在的 table 添加一个 FOREIGN KEY在以下行的 CREATE TABLE salesorders 语句中

FOREIGN KEY (customer_id) REFERENCES customers(customer_id)

为了解决这个问题,我在 SalesOrders CREATE 语句之前写了 CREATE TABLE Customers 部分。

这只是 1 个问题。您还在 Donuts table 之前创建 SalesOrders table 并尝试添加 FOREIGN KEY 约束。

最后,你在Donutstable中没有任何记录,所以我为你创建了一个Jelly Donut:)

为了完整起见,下面发布了 SQLFiddle 代码。

CREATE TABLE customers ( 
  customer_id INT(10) NOT NULL AUTO_INCREMENT, 
  customer_name VARCHAR(100) NOT NULL,
  PRIMARY KEY (customer_id)
  );

CREATE TABLE donuts (
  donut_id INT(10) NOT NULL AUTO_INCREMENT, 
  name VARCHAR(30), 
  description VARCHAR(50), 
  unit_price DECIMAL(8,3), 
  PRIMARY KEY (donut_id) );

INSERT INTO donuts (donut_id,name,description,unit_price)  
VALUES (1,"Jelly Donut","Delicious Donut filled with Raspberry Jelly inside",1.99);

CREATE TABLE salesorders ( 
  donut_order_id INT(10) NOT NULL AUTO_INCREMENT, 
  customer_id INT, date DATETIME, 
  special_handling_note TEXT, 
  PRIMARY KEY (donut_order_id), 
  FOREIGN KEY (customer_id) REFERENCES customers(customer_id) );

INSERT INTO salesorders ( donut_order_id,date,special_handling_note )
VALUES( 0000001,"2018-04-22","Please include plates and napkins" );

CREATE TABLE salesorderslineitem ( 
  donut_order_id INT(10) NOT NULL, 
  donut_id INT(10) NOT NULL, qty INT(10) NOT NULL, 
  PRIMARY KEY (donut_order_id, donut_id),
  FOREIGN KEY (donut_order_id) 
  REFERENCES salesorders(donut_order_id), 
  FOREIGN KEY (donut_id) REFERENCES donuts(donut_id) );

INSERT INTO salesorderslineitem (donut_order_id,donut_id, qty) VALUES (0000001,1, 12);