涉及非外键列的MySQL约束

时间:2018-04-09 23:26:21

标签: mysql constraints

我有一个mySQL架构,其中有两个表:stay和service_records。

Columns for service_records: `stayId`, `serviceCode`, `staffId`, `serviceDate`, `serviceTime`

Columns for stays: `stayId`, `hotelId`, ...`, `checkinDate`, `checkinTime`, `checkoutDate`, `checkoutTime`, `billingId`

以下是每个表的创建表脚本:

*************************** 1. row ***************************
       Table: stays
Create Table: CREATE TABLE `stays` (
  `stayId` int(9) unsigned NOT NULL AUTO_INCREMENT,
  `hotelId` int(9) unsigned NOT NULL,
  `roomNumber` varchar(5) NOT NULL,
  `customerId` int(9) unsigned NOT NULL,
  `numOfGuests` tinyint(4) NOT NULL,
  `checkinDate` date DEFAULT NULL,
  `checkinTime` time DEFAULT NULL,
  `checkoutDate` date DEFAULT NULL,
  `checkoutTime` time DEFAULT NULL,
  `billingId` int(9) unsigned NOT NULL,
  PRIMARY KEY (`stayId`),
  UNIQUE KEY `billingId` (`billingId`),
  KEY `hotelId` (`hotelId`,`roomNumber`),
  KEY `customerId` (`customerId`),
  CONSTRAINT `stays_ibfk_1` FOREIGN KEY (`hotelId`, `roomNumber`)     REFERENCES `rooms` (`hotelId`, `roomNumber`),
  CONSTRAINT `stays_ibfk_2` FOREIGN KEY (`customerId`) REFERENCES     `customers` (`customerId`),
  CONSTRAINT `stays_ibfk_3` FOREIGN KEY (`billingId`) REFERENCES     `billing_info` (`billingId`)
) ENGINE=InnoDB AUTO_INCREMENT=201 DEFAULT CHARSET=latin1

| service_records | CREATE TABLE `service_records` (
  `stayId` int(9) unsigned NOT NULL,
  `serviceCode` char(4) NOT NULL,
  `staffId` int(9) unsigned NOT NULL,
  `serviceDate` date NOT NULL,
  `serviceTime` time NOT NULL,
  PRIMARY KEY (`stayId`,`serviceDate`,`serviceTime`),
  KEY `serviceCode` (`serviceCode`),
  KEY `staffId` (`staffId`),
  CONSTRAINT `service_records_ibfk_1` FOREIGN KEY (`stayId`) REFERENCES `stays` (`stayId`),
  CONSTRAINT `service_records_ibfk_2` FOREIGN KEY (`serviceCode`) REFERENCES `services` (`serviceCode`),
  CONSTRAINT `service_records_ibfk_3` FOREIGN KEY (`staffId`) REFERENCES     `service_staff` (`staffId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
问题1:我想确保服务时间在停留时间窗口内。我想知道如何使用MySQL约束来强制服务时间处于停留范围内!

问题2:如果我的表中已有记录,那么可以使用适当的列约束来更新表(不删除表)吗?当然,我会编辑受影响的记录。

非常感谢您的帮助。

CS

0 个答案:

没有答案