我有这个代码来创建一些表:
CREATE TABLE Appelations (
No int AUTO_INCREMENT,
Appelation varchar(35),
County varchar(20),
State varchar(15),
Area varchar(25),
IsAVA varchar(3),
PRIMARY KEY (No)
);
CREATE TABLE Grapes (
ID int AUTO_INCREMENT,
Grape varchar(25),
Color varchar(10),
PRIMARY KEY (ID)
);
CREATE TABLE Wine (
No int AUTO_INCREMENT,
Grape varchar(25),
Winery varchar(40),
Appelation varchar(35),
Name varchar(40),
Year year,
Price int,
Score int,
Cases int,
PRIMARY KEY (No),
FOREIGN KEY (Grape) REFERENCES Grapes(Grape),
FOREIGN KEY (Appelation) REFERENCES Appelations(Appelation)
);
但是当我运行它时,我收到了这个错误:
ERROR 1005(HY000):无法创建表'db.Wine'(错误号:150)
有谁知道如何解决这个问题?感谢。
答案 0 :(得分:1)
您need indexes on your foreign keys:" MySQL需要外键和引用键的索引,这样外键检查可以很快,不需要进行表扫描。"
示例:http://sqlfiddle.com/#!9/d228b8
CREATE TABLE Appelations (
No int AUTO_INCREMENT,
Appelation varchar(35),
County varchar(20),
State varchar(15),
Area varchar(25),
IsAVA varchar(3),
INDEX appelation_ind (Appelation), /*<---*/
PRIMARY KEY (No)
);
CREATE TABLE Grapes (
ID int AUTO_INCREMENT,
Grape varchar(25),
Color varchar(10),
INDEX grape_ind (Grape), /*<---*/
PRIMARY KEY (ID)
);
CREATE TABLE Wine (
No int AUTO_INCREMENT,
Grape varchar(25),
Winery varchar(40),
Appelation varchar(35),
Name varchar(40),
Year year,
Price int,
Score int,
Cases int,
PRIMARY KEY (No),
FOREIGN KEY (Grape) REFERENCES Grapes(Grape),
FOREIGN KEY (Appelation) REFERENCES Appelations(Appelation)
);
答案 1 :(得分:0)
这是因为表中的FOREIGH KEY
列引用了既不是主键也没有索引的列(在父表中)。您可以更改类型,并使其分别指向ID
和No
表的Grapes
和Appelations
列,例如:
CREATE TABLE Wine (
No int AUTO_INCREMENT,
Grape_id int,
Winery varchar(40),
Appelation_no int,
Name varchar(40),
Year year,
Price int,
Score int,
Cases int,
PRIMARY KEY (No),
FOREIGN KEY (Grape_id) REFERENCES Grapes(id),
FOREIGN KEY (Appelation_no) REFERENCES Appelations(No)
);
这里是 SQL Fiddle 。