Mysql的。如何使用外键列的空值将行插入子表

时间:2014-08-12 12:16:04

标签: mysql sql insert null cascade

我创建了两个表。首先是'建筑物'第二个是' rooms'

 CREATE TABLE buildings (
  building_no int(11) NOT NULL AUTO_INCREMENT,
  building_name varchar(255) NOT NULL,
  address varchar(355) NOT NULL,
  PRIMARY KEY (building_no)
 ) ENGINE=InnoDB;


 CREATE TABLE rooms (
  room_no int(11) NOT NULL AUTO_INCREMENT,
  room_name varchar(255) NOT NULL,
  building_no int(11) NULL,
  PRIMARY KEY (room_no),
  KEY building_no (building_no),
  CONSTRAINT rooms_ibfk_1 
  DEFAULT NULL
  FOREIGN KEY (building_no) 
  REFERENCES buildings (building_no) 
  ON DELETE RESTRICT
  ON UPDATE CASCADE
 ) ENGINE=InnoDB;

所以当我添加一个带有NULL列的新房间' building_no'我收到一条消息:

  

无法添加或更新子行:外键约束失败(rooms,CONSTRAINT rooms_ibfk_1 FOREIGN KEY(building_no)参考buildingsbuilding_no )ON UPDATE CASCADE)

为什么会发生这种情况以及如何解决?

1 个答案:

答案 0 :(得分:0)

对于创建房间表,您可以使用此查询

CREATE TABLE IF NOT EXISTS `rooms` (
  `room_no` int(11) NOT NULL AUTO_INCREMENT,
  `room_name` varchar(255) NOT NULL,
  `building_no` int(11) DEFAULT NULL,
  PRIMARY KEY (`room_no`),
  KEY `building_no` (`building_no`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

要在房间中插入而不是关系,您必须先确保构建表中存在主键,这样您才能首先运行此查询以在建筑物上插入:

INSERT INTO `yourdb`.`buildings` (
`building_no` ,
`building_name` ,
`address`
)
VALUES (
NULL , 'b1', 'address of b1'
);

然后插入房间表并为您的特定建筑定义房间,您可以使用此查询:

INSERT INTO `yourdb`.`rooms` (
`room_no` ,
`room_name` ,
`building_no`
)
VALUES (
'1', 'room1', '1'
);