SQL - 无法添加外键约束

SQL - Cannot add foreign key constraint

我对编写 SQL 代码完全陌生,我正在尝试 运行 一个简单的 table 创建,但是我找不到我的编程错误在哪里,并且作为我是全新的我正在为这个创作而苦苦挣扎。

这是我正在做的一个学校项目,希望有人能提供帮助。

我在 'SQLFiddle' 中收到的错误是 "Cannot add foreign key constraint" 以下代码:

CREATE TABLE invoice(
  invoice_id INT NOT NULL,
  customer_id INT NOT NULL,
  order_date DATE NULL,
  spec_order_note VARCHAR(45) NULL,
  PRIMARY KEY(invoice_id, customer_id),
  FOREIGN KEY (customer_id)
  REFERENCES customer.customer_id
  ON DELETE CASCADE
  ON UPDATE CASCADE
);

CREATE TABLE line_item (
  invoice_id INT NOT NULL,
  donut_id INT NOT NULL,
  quantity INT NULL
  CONSTRAINT donut_invoice
  FOREIGN KEY invoice_id
  REFERENCES invoice.invoice_id
  ON DELETE RESTRICT
  ON UPDATE RESTRICT
)

CREATE TABLE donut (
  donut_id INT NOT NULL,
  donut_name VARCHAR(15) NULL,
  description VARCHAR(30) NULL,
  unit_price INT NULL
  PRIMARY KEY(donut_id),
)

CREATE TABLE customer (
  customer_id INT NOT NULL,
  last_name VARCHAR(15) NULL,
  first_name VARCHAR(10) NULL,
  street_add VARCHAR(20) NULL,
  apt_num INT NULL,
  city VARCHAR(20) NULL,
  state VARCHAR(15) NULL,
  zip_code INT NULL,
  home_phone VARCHAR(10) NULL,
  mobile_phone VARCHAR(10) NULL,
  other_phone VARCHAR(10) NULL,
  customer_notes VARCHAR(45) NULL
  PRIMARY KEY(customer_id),
)

非常感谢任何帮助。

您只能在外部约束中引用现有的 table 和列。所以如果你想在invoice的外键中引用customer table,你需要在invoice之前创建customer或者额外添加外键约束使用 ALTER TABLE.

除此之外,您的代码中存在一些语法错误,例如缺少分号和错放(缺少和附加)逗号。

工作代码:

CREATE TABLE customer (
  customer_id INT NOT NULL,
  last_name VARCHAR(15) NULL,
  first_name VARCHAR(10) NULL,
  street_add VARCHAR(20) NULL,
  apt_num INT NULL,
  city VARCHAR(20) NULL,
  state VARCHAR(15) NULL,
  zip_code INT NULL,
  home_phone VARCHAR(10) NULL,
  mobile_phone VARCHAR(10) NULL,
  other_phone VARCHAR(10) NULL,
  customer_notes VARCHAR(45) NULL,
  PRIMARY KEY(customer_id)
);

CREATE TABLE invoice(
  invoice_id INT NOT NULL,
  customer_id INT NOT NULL,
  order_date DATE NULL,
  spec_order_note VARCHAR(45) NULL,
  PRIMARY KEY(invoice_id, customer_id),
  FOREIGN KEY (customer_id)
  REFERENCES customer (customer_id)
  ON DELETE CASCADE
  ON UPDATE CASCADE
);

CREATE TABLE line_item (
  invoice_id INT NOT NULL,
  donut_id INT NOT NULL,
  quantity INT NULL,
  CONSTRAINT donut_invoice
  FOREIGN KEY (invoice_id)
  REFERENCES invoice (invoice_id)
  ON DELETE RESTRICT
  ON UPDATE RESTRICT
);

CREATE TABLE donut (
  donut_id INT NOT NULL,
  donut_name VARCHAR(15) NULL,
  description VARCHAR(30) NULL,
  unit_price INT NULL,
  PRIMARY KEY(donut_id)
);

http://sqlfiddle.com/#!9/36b044