ALTER TABLE时不存在SQL键列

时间:2017-09-27 17:39:40

标签: mysql sql

ALTER TABLE book
ADD FOREIGN KEY (category_id)
REFERENCES category (category_id)
ON DELETE CASCADE
ON UPDATE CASCADE;

每当我运行这个ALTER TABLE语句时,它都会继续回复,"错误代码:1072。键列' category_id'不存在。"

我确定这是一个简单的解决方法,但我在向其中一个表添加外键时遇到问题。我上周刚开始学习SQL,所以任何帮助都将不胜感激!

我的CREATE TABLE语句如下:

CREATE TABLE IF NOT EXISTS book
(book_id INT not null PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(100) not null,
description TEXT not null,
price DEC(18,2) not null
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS category
(category_id INT not null PRIMARY KEY AUTO_INCREMENT,
code1 VARCHAR(20) not null,
name1 VARCHAR(100) not null
) ENGINE=InnoDB;

2 个答案:

答案 0 :(得分:0)

CREATE TABLE IF NOT EXISTS category
(category_id INT not null PRIMARY KEY AUTO_INCREMENT,
code1 VARCHAR(20) not null,
name1 VARCHAR(100) not null
) ENGINE=InnoDB;

此表具有Primay Key category_id,但下表没有Column as" category_id"这是在Alter Command.Add中引用的 列" category_id在下表中,然后执行Alter命令。

CREATE TABLE IF NOT EXISTS book
(book_id INT not null PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(100) not null,
description TEXT not null,
price DEC(18,2) not null
) ENGINE=InnoDB;

答案 1 :(得分:0)

这是完整的脚本

CREATE TABLE IF NOT EXISTS book
(book_id INT not null PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(100) not null,
description TEXT not null,
price DEC(18,2) not null,
category_id INT not null 
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS category
(category_id INT not null PRIMARY KEY AUTO_INCREMENT,
code1 VARCHAR(20) not null,
name1 VARCHAR(100) not null
) ENGINE=InnoDB;

ALTER TABLE book
ADD FOREIGN KEY (category_id)
REFERENCES category (category_id)
ON DELETE CASCADE
ON UPDATE CASCADE;