我正在编写酒店数据库,并且对DATEDIFF函数有疑问。我有一个包含来宾ID,到达日期,出发时间的表,并且我希望DATEDIFF(出发时间,到达时间)写入同一表的另一列。我怎样才能做到这一点?我试图制作两个表,但是一次工作,当我添加另一个来宾时,每次弹出主键重复错误。
当我创建空列'length'并尝试保存选择时,在此列中显示错误。码:插入预订(length_of_stay)中,从预订中选择DATEDIFF(出发,到达);错误:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`input_qt_plus`.`reservations`, CONSTRAINT `fk_reservations_guests` FOREIGN KEY (`guests_id_guests`) REFERENCES `guests` (`id_guests`) ON DELETE NO ACTION ON UPDATE NO ACTION)
表格:
这是客人的桌子:
CREATE TABLE IF NOT EXISTS `input_qt_plus`.`guests` (
`id_guests` INT NOT NULL AUTO_INCREMENT,
`first_name` VARCHAR(45) NOT NULL,
`last_name` VARCHAR(45) NOT NULL,
`email` VARCHAR(45) NOT NULL,
`phone` VARCHAR(45) NOT NULL,
`id_num` VARCHAR(45) NULL,
PRIMARY KEY (`id_guests`))
ENGINE = InnoDB;
这是有保留的表:
CREATE TABLE IF NOT EXISTS `input_qt_plus`.`reservations` (
`id_res` INT NOT NULL AUTO_INCREMENT,
`guests_id_guests` INT NOT NULL,
`arrival` DATE NOT NULL,
`departure` DATE NOT NULL,
PRIMARY KEY (`id_res`),
INDEX `fk_reservations_guests_idx` (`guests_id_guests` ASC),
CONSTRAINT `fk_reservations_guests`
FOREIGN KEY (`guests_id_guests`)
REFERENCES `input_qt_plus`.`guests` (`id_guests`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
尝试此查询:希望它能正常工作
INSERT INTO your_table (field1, field2, arrival, departure, length)
VALUES (value1, value2, arrivalDate, departureDate, DATEDIFF(day,arrivalDate, departureDate))
由于要更新同一张表,因此应两次使用它。首先将列添加到表中(假设您将其命名为stay_for),然后像这样更新它-更新预订R内部联接保留R2在R2.id_res = R.id_res设置R.stay_for = DATEDIFF(R2.departure,R2.arrival);