sql fiddle-无法添加外键约束

ev7lccsx  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(384)

我在为salesorderslineitem表构建架构时遇到问题。甚至当我试图用小提琴自己构建模式的时候。我得到一个错误消息不能添加外键约束。。。在这里我的表一起试图让新的salesorderslineitem表工作。谢谢大家!

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)
8yparm6h

8yparm6h1#

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

这是一把小提琴。http://sqlfiddle.com/#!9/5071d0号

第一个问题是还没有定义 CREATE Statement 对于 Customers 表中不存在的表中添加外键 CREATE TABLE salesorders 下一行的语句 FOREIGN KEY (customer_id) REFERENCES customers(customer_id) 为了解决这个问题,我写了 CREATE TABLE Customers 前一节 SalesOrders 创建语句。
这只是一个问题。您还创建了 SalesOrders 前桌 Donuts 表并尝试添加 FOREIGN KEY 约束。
最后,你没有任何记录 Donuts 表,所以我创建了一个 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);

相关问题