您可以使用MySQL datetime function date_add() 来计算目标return_date。假设借书的日期为loan_date,时长存储在loan_duration,以天为单位:
select
book_id,
student_id,
loan_date,
date_add(loan_date, interval loan_duration day) return_date
from loan_table
在更新语句中:
update loan_table
set return_date = date_add(loan_date, interval loan_duration day)
where return_date is null -- only compute the return_dates that were not yet computed
编辑
如果您希望该值是自动生成的,一个选项是使用生成的存储(或虚拟)列(自 MySQL 5.7 起可用)。这通过定义一个计算规则来工作,当记录被插入或更新时,MySQL 将自动应用该规则。
Demo on DB Fiddle:
-- set up
create table loan_table(
id int primary key auto_increment,
book_id int,
student_id int,
loan_date date,
loan_duration int,
-- here is the generated column
return_date date
as (date_add(loan_date, interval loan_duration day)) stored
);
-- perform an insert
insert into loan_table(book_id, student_id, loan_date, loan_duration)
values(1, 1, '2019-11-02', 3)
-- check the computed value
select * from loan_table;
编号 | book_id |学生ID |贷款日期 |贷款期限 |归期
-: | ------: | ---------: | :--------- | ------------: | :----------
1 | 1 | 1 | 2019-11-02 | 3 | 2019-11-05