0

我在为我的 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)
4

1 回答 1

0

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

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

第一个问题是尚未CREATE StatementCustomers表定义,并试图CREATE TABLE salesorders在下一行的语句中向这个不存在的表添加一个 FOREIGN KEY

FOREIGN KEY (customer_id) REFERENCES customers(customer_id)

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

那只是1个问题。您还在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);
于 2018-04-24T19:38:34.147 回答