无法在Mysql中创建外部约束

时间:2015-09-22 19:52:49

标签: mysql

这是我试图运行的脚本

CREATE TABLE IF NOT EXISTS `store` (
`store_id` INT NOT NULL AUTO_INCREMENT,
`store_name` VARCHAR(1024) NOT NULL,
`store_user` INT NOT NULL,
`store_address` INT NOT NULL,
`store_type` INT NOT NULL,
`created_date` DATETIME NOT NULL,
`updated_date` DATETIME NOT NULL,
PRIMARY KEY (`store_id`)
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS `store_address` (
`address_id` INT NOT NULL AUTO_INCREMENT,
`address_line_1` VARCHAR(1024) NOT NULL,
`address_line_2` VARCHAR(1024) NOT NULL,
`address_line_3` VARCHAR(1024) NULL,
`city` VARCHAR(45) NOT NULL,
`locality` VARCHAR(100) NOT NULL,
`pincode` CHAR(6) NOT NULL,
`latitude` DECIMAL(8,6) NULL,
`longitude` DECIMAL(9,6) NULL,
`state` VARCHAR(45) NOT NULL,
`created_date` DATETIME NOT NULL,
`updated_date` DATETIME NOT NULL,
PRIMARY KEY (`address_id`),
CONSTRAINT `FK_STR_STR_ADR`
FOREIGN KEY (`address_id`)
REFERENCES `store` (`store_address`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;

我收到此错误 - Error Code: 1215. Cannot add foreign key constraint 不知道DDL有什么问题

1 个答案:

答案 0 :(得分:0)

两个问题:
1.使用unsigned int作为主键(编辑:这是一个好主意,但不是问题)
2. store.store地址必须是store表中的键才能在store_address表中的外键约束中使用它

 CREATE TABLE IF NOT EXISTS `store` (
 `store_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `store_name` VARCHAR(1024) NOT NULL,
 `store_user` INT NOT NULL,
 `store_address` int(10) unsigned NOT NULL DEFAULT 0,
 `store_type` INT NOT NULL,
 `created_date` DATETIME NOT NULL,
 `updated_date` DATETIME NOT NULL,
 PRIMARY KEY (`store_id`),
 KEY (`store_address`)
 ) ENGINE = InnoDB;

 CREATE TABLE IF NOT EXISTS `store_address` (
 `address_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `address_line_1` VARCHAR(1024) NOT NULL,
 `address_line_2` VARCHAR(1024) NOT NULL,
 `address_line_3` VARCHAR(1024) NULL,
 `city` VARCHAR(45) NOT NULL,
 `locality` VARCHAR(100) NOT NULL,
 `pincode` CHAR(6) NOT NULL,
 `latitude` DECIMAL(8,6) NULL,
 `longitude` DECIMAL(9,6) NULL,
 `state` VARCHAR(45) NOT NULL,
 `created_date` DATETIME NOT NULL,
 `updated_date` DATETIME NOT NULL,
 PRIMARY KEY (`address_id`),
 CONSTRAINT `FK_STR_STR_ADR` FOREIGN KEY (`address_id`) REFERENCES `store` (`store_address`)
 )ENGINE = InnoDB;