我正在尝试创建一个数据库,但是收到一个奇怪的错误......这是我的代码
DROP TABLE IF EXISTS `Person`;
DROP TABLE IF EXISTS `Address`;
DROP TABLE IF EXISTS `Email`;
DROP TABLE IF EXISTS `Airport`;
DROP TABLE IF EXISTS `Customer`;
CREATE TABLE Address
(
AddressID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(AddressID),
AddressStreet VARCHAR(255),
AddressCity VARCHAR(255),
AddressState VARCHAR(255),
AddressZip VARCHAR(255),
AddressCountry VARCHAR(255)
);
CREATE TABLE Email
(
EmailID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(EmailID),
EmailAddress VARCHAR(255)
);
CREATE TABLE Person
(
PersonID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PersonID),
PersonCode VARCHAR(255),
PersonLastName VARCHAR(255),
PersonFirstName VARCHAR(255),
AddressID INT NOT NULL,
FOREIGN KEY `fk_Person_to_Address` (AddressID) REFERENCES Address(AddressID),
PersonPhone VARCHAR(255),
EmailID INT NOT NULL,
FOREIGN KEY `fk_Person_to_Email` (EmailID) REFERENCES Email(EmailID)
);
CREATE TABLE Airport
(
AirportID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(AirportID),
AirportCode VARCHAR(255),
AirportName VARCHAR(255),
AddressID INT NOT NULL,
FOREIGN KEY `fk_Airport_to_Address` (AddressID) REFERENCES Address(AddressID),
AirportLatDeg INT NOT NULL,
AirportLatMin INT NOT NULL,
AirportLongDeg INT NOT NULL,
AirportLongMin INT NOT NULL,
AirportPassFacilityFee FLOAT NOT NULL
);
CREATE TABLE Customer
(
CustomerID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(CustomerID),
CustomerCode VARCHAR(255),
CustomerType VARCHAR(255),
PrimaryContact VARCHAR(255),
FOREIGN KEY `fk_Customer_to_Person` (PrimaryContact) REFERENCES Person(PersonID),
CustomerName VARCHAR(255),
CustomerAirlineMiles FLOAT NOT NULL
);
在我到达Customer表之前,一切都很顺利,我尝试重命名其中一个外键。这是我得到的错误......
Error Code: 1005. Can't create table 'myName.Customer' (errno: 150)
我试图查看此错误的其他一些示例,但我不理解该问题。是因为我正在尝试重命名Customer表中的外键吗?我想要的是从Person表中获取PersonID,但在Customer表中将其重命名为primaryContact。我该如何解决这个问题?
答案 0 :(得分:2)
创建外键时,数据类型应与主键的数据类型匹配。更改PrimaryContact
表格中的Customer
字段以匹配PersonId
的数据类型,在本例中为int
:
CREATE TABLE Customer
(
CustomerID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(CustomerID),
CustomerCode VARCHAR(255),
CustomerType VARCHAR(255),
PrimaryContact int,
FOREIGN KEY `fk_Customer_to_Person` (PrimaryContact) REFERENCES Person(PersonID),
CustomerName VARCHAR(255),
CustomerAirlineMiles FLOAT NOT NULL
);
列必须与标题为Using FOREIGN KEY Constraints的手册页中所示的类型相同:
外键和引用键中的对应列必须 有类似的数据类型。整数类型的大小和符号必须是 相同。字符串类型的长度不必相同。对于 非二进制(字符)字符串列,字符集和排序规则 必须是一样的。