当我将文件导入phpmyadmin时,出现以下错误:
1005-无法创建表“test\u db”。“part\u order”(errno:150“外键约束格式不正确”)
我检查了很多次语法,但看不出哪里不对。我试着用 INDEX
以及 CONSTRAINT
但没有成功。任何帮助都将不胜感激。
CREATE TABLE IF NOT EXISTS `all_products` (
`product_id` int(10) NOT NULL AUTO_INCREMENT,
`product_name` VARCHAR(100) NOT NULL,
`product_price` decimal(10,2) NOT NULL,
`product_description` VARCHAR(1000) NOT NULL,
PRIMARY KEY(`product_id`, `product_name`)
) ENGINE=InnoDB DEFAULT CHARSET=UTF8;
CREATE TABLE IF NOT EXISTS `product_color` (
`color_id` int(10) NOT NULL AUTO_INCREMENT,
`product_id` INT(10) NOT NULL,
`color_name` VARCHAR(100) NOT NULL,
PRIMARY KEY(`color_id`, `color_name`),
FOREIGN KEY(`product_id`) REFERENCES all_products(`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=UTF8;
CREATE TABLE IF NOT EXISTS `users` (
`user_id` INT(10) NOT NULL AUTO_INCREMENT,
`first_name` VARCHAR(100) NOT NULL,
`last_name` VARCHAR(100) NOT NULL,
`email` VARCHAR(100) NOT NULL,
`password` VARCHAR(200) NOT NULL,
`address` VARCHAR(200) NOT NULL,
`city` VARCHAR(100) NOT NULL,
`post_code` VARCHAR(8) NOT NULL,
PRIMARY KEY(`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=UTF8;
CREATE TABLE IF NOT EXISTS `part_order` (
`order_number` INT(10) NOT NULL ,
`product_name` VARCHAR(100) NOT NULL,
`color_name` VARCHAR(100) NOT NULL,
`qty` INT(10) NOT NULL,
PRIMARY KEY(`order_number`),
INDEX(`order_number`),
CONSTRAINT FOREIGN KEY(`product_name`) REFERENCES
all_products(`product_name`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY(`color_name`) REFERENCES
product_color(`color_name`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=UTF8;
CREATE TABLE IF NOT EXISTS `orders` (
`order_number` INT(10) NOT NULL,
`user_id` INT(10) NOT NULL,
Date DATETIME DEFAULT CURRENT_TIMESTAMP,
`total_cost` INT(10) NOT NULL,
`status` VARCHAR(50) NOT NULL,
PRIMARY KEY(`status`),
CONSTRAINT FOREIGN KEY(`order_number`) REFERENCES
part_order(`order_number`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY(`user_id`) REFERENCES
users(`user_id`) ON DELETE CASCADE ON UPDATE CASCADE
)
1条答案
按热度按时间brccelvz1#
mysql需要引用列上的索引(
product_name
以及color_name
). 添加INDEX(product_name)
到all_products
表和INDEX(color_name)
到product_color
table从文档中:
mysql需要外键和引用键的索引,这样外键检查可以很快,并且不需要表扫描。在引用表中,必须有一个索引,其中外键列按相同顺序列为第一列。如果引用表不存在,则会自动在引用表上创建这样的索引。如果您创建另一个可用于强制外键约束的索引,则稍后可能会自动删除此索引。索引名称(如果给定)如前所述使用。