我有一个 SQL 数据库,其中包含有关学生和他们借阅的书籍的信息。
我有一张外借表,其中包括book_id
、student_id
、借书日期和可以保留的天数。
我想通过添加这本书拍摄日期的天数来自动生成 return_date
。我如何使用 MySQL Workbench 执行此操作?
最佳答案
您可以使用 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 将在插入或更新记录时自动应用该规则。
-- 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;
id | book_id | student_id | loan_date | loan_duration | return_date -: | ------: | ---------: | :--------- | ------------: | :---------- 1 | 1 | 1 | 2019-11-02 | 3 | 2019-11-05
关于mysql - 在表 SQL 中生成日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58669535/