我正在创建一个表,通过 now() 函数获取输入时间。每个数据的有效期为两个小时。所以我需要在结束时间列中自动添加时间
CREATE TABLE `mdiner_test`.`table_assign_mgr` (
`resid` INT NOT NULL AUTO_INCREMENT,
`custname` VARCHAR(45) NOT NULL DEFAULT 'Guest',
`custemail` VARCHAR(45) NOT NULL DEFAULT 'info@si.com',
`custmobile` VARCHAR(45) NOT NULL DEFAULT '98989898',
`isactive` TINYINT NOT NULL DEFAULT 1,
`starttime` DATETIME NOT NULL DEFAULT now(),
`endtime` DATETIME NOT NULL DEFAULT DATE_ADD(now(), INTERVAL 2 HOUR),
PRIMARY KEY (`resid`));
最佳答案
这似乎是一个不必要的列,但您也许可以使用生成的列(取决于您的 mysql 版本)https://dev.mysql.com/doc/refman/5.7/en/create-table-generated-columns.html但你将失去提供结束时间的能力。
drop table if exists t;
CREATE TABLE t (
`resid` INT NOT NULL AUTO_INCREMENT,
`custname` VARCHAR(45) NOT NULL DEFAULT 'Guest',
`custemail` VARCHAR(45) NOT NULL DEFAULT 'info@si.com',
`custmobile` VARCHAR(45) NOT NULL DEFAULT '98989898',
`isactive` TINYINT NOT NULL DEFAULT 1,
`starttime` DATETIME NOT NULL DEFAULT now(),
`endtime` DATETIME as (DATE_ADD(starttime, INTERVAL 2 HOUR)),
PRIMARY KEY (`resid`));
insert into t(resid) values (1);
select * from t;
+-------+----------+-------------+------------+----------+---------------------+---------------------+
| resid | custname | custemail | custmobile | isactive | starttime | endtime |
+-------+----------+-------------+------------+----------+---------------------+---------------------+
| 1 | Guest | info@si.com | 98989898 | 1 | 2019-07-16 08:27:58 | 2019-07-16 10:27:58 |
+-------+----------+-------------+------------+----------+---------------------+---------------------+
1 row in set (0.00 sec)
如果您无法使用生成的列,您可以使用触发器。
关于mysql - 在mysql中创建create语句时需要在列中添加两个小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57051833/