下面是我的代码,请大家看一下并帮我指出解决方案。我正在尝试创建数据库并用于我的 Spring Boot 项目。
DROP DATABASE IF EXISTS recipeDb;
CREATE DATABASE recipeDb;
USE recipeDb;
DROP TABLE IF EXISTS recipe;
CREATE TABLE recipe (
id int NOT NULL,
recipeTitle varchar(30),
description varchar(255),
cookTime int,
ingredientID int,
stepID int,
PRIMARY KEY(id)
);
ALTER TABLE recipe
ADD FOREIGN KEY (ingredientID) REFERENCES ingredient(id);
ADD FOREIGN KEY (stepID) REFERENCES step(id);
DROP TABLE IF EXISTS category;
CREATE TABLE category (
id int NOT NULL,
categoryTitle varchar(20),
PRIMARY KEY(id)
);
DROP TABLE IF EXISTS recipe_category;
CREATE TABLE recipe_category (
recipeID int,
categoryID int
);
DROP TABLE IF EXISTS step;
CREATE TABLE step (
id int NOT NULL,
stepDesctiption varchar(255),
PRIMARY KEY(id)
);
DROP TABLE IF EXISTS ingredient;
CREATE TABLE ingredient (
id int NOT NULL,
ingredientName varchar(255),
PRIMARY KEY(id)
);
最佳答案
尝试将更改表移至代码底部
ALTER TABLE recipe
ADD FOREIGN KEY (ingredientID) REFERENCES ingredient(id),
ADD FOREIGN KEY (stepID) REFERENCES step(id),
编辑
尝试在CREATE TABLE
中添加外键怎么样?将其也移至代码底部。
DROP TABLE IF EXISTS recipe;
CREATE TABLE recipe (
id int NOT NULL,
recipeTitle varchar(30),
description varchar(255),
cookTime int,
ingredientID int FOREIGN KEY REFERENCES ingredient(id),
stepID int FOREIGN KEY REFERENCES step(id),
PRIMARY KEY(id)
);
关于mysql - 我想在 mySQL 中运行我的脚本,但在我运行它时它一直显示这个!错误 1215 (HY000) 在第 18 行 : Cannot add foreign key constraint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52981225/