2

我正在尝试在 MySQL 中创建以下表。第一个:

CREATE TABLE IF NOT EXISTS address(
  address_id INT NOT NULL AUTO_INCREMENT,
  address_region VARCHAR(10) NOT NULL,
  address_country VARCHAR(20) NOT NULL,
  address_city VARCHAR(30) NOT NULL,
  PRIMARY KEY(address_id))ENGINE = InnoDB;

我成功创建了它,但是当我尝试创建另一个表时,如下所示

CREATE TABLE IF NOT EXISTS spot(
  spot_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  spot_address INT(11) NOT NULL,
  spot_name VARCHAR(50) NOT NULL,
  spot_desc VARCHAR(500) DEFAULT ' ',
  spot_speadd VARCHAR(100) NOT NULL,
  spot_viewtime INT DEFAULT 0,
  FOREIGN KEY(spot_address)
  REFERENCES address(address_id)
  ON DELETE SET NULL
  ON UPDATE SET NULL);

我收到一个错误:

ERROR 1215 (HY000): 无法添加外键约束

为什么这个创建表语句失败?

4

2 回答 2

5

您在表中有NOT NULL约束,然后尝试在父表中将其设置为删除或更新。spot_addressspotNULLaddress

于 2013-05-17T11:42:08.460 回答
0

你可以试试这个:

CREATE TABLE IF NOT EXISTS address
(
address_id INT NOT NULL AUTO_INCREMENT,
address_region VARCHAR(10) NOT NULL,
address_country VARCHAR(20) NOT NULL,
address_city VARCHAR(30) NOT NULL,
PRIMARY KEY(address_id)
)ENGINE = INNODB;




CREATE TABLE IF NOT EXISTS `spot`
(
  `spot_id` INT(11) NOT NULL AUTO_INCREMENT,
  `spot_address` INT(11) NOT NULL,
  `spot_name` VARCHAR(50) NOT NULL,
  `spot_desc` VARCHAR(500) DEFAULT ' ',
  `spot_speadd` VARCHAR(100) NOT NULL,
  `spot_viewtime` INT(11) DEFAULT '0',
  PRIMARY KEY (`spot_id`),
  KEY `spot_address` (`spot_address`),
  CONSTRAINT `spot_ibfk_1` FOREIGN KEY (`spot_address`) REFERENCES `address` (`address_id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
于 2013-05-17T12:01:03.393 回答