【问题标题】:Generating a date in a table SQL在表 SQL 中生成日期
【发布时间】:2019-11-02 08:44:57
【问题描述】:

我有一个 SQL 数据库,其中包含有关学生和他们借阅的书籍的信息。

我有一张借阅表,其中包括book_idstudent_id、借书的日期和可以保留的天数。

我想通过添加图书拍摄日期的天数来自动生成return_date。如何使用 MySQL Workbench 做到这一点?

【问题讨论】:

标签: mysql sql date generate


【解决方案1】:

您可以使用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

【讨论】:

  • 我明白了,我可以很容易地写这个。我实际上想自动生成它。例如,当我在表中插入loan_date 和列restore_date 自动更新的天数时。例如,我希望它像自动增量一样工作。
  • @AdelinaK:好的。我用建议使用生成列的解决方案更新了我的答案。
【解决方案2】:

您可以使用区间和 + 的组合:

select book_id
       , student_id
       , date_taken
       , number_od_days
       , (date_taken + interval number_od_days day) as return_date
from loans;

这是DEMO中的示例

如果您希望此列自动递增,我建议您在表中创建一个触发器:

CREATE TRIGGER rentcheck 
BEFORE INSERT ON loans 
FOR EACH ROW 
begin
    if new.number_od_days < 0 or new.number_od_days is null then
      signal sqlstate '45000';
    else
      set new.return_date = (new.date_taken + interval new.number_od_days day);
    end if;
end;

使用它,您可以控制列 number_of_days 是否为负数或不输入,因为这将导致非逻辑数据。这是触发器的演示:DEMO

【讨论】:

    【解决方案3】:

    你可以在mysql中使用变量:

    set @days = 10;
    set @mydate := DATE_ADD("2019-11-01", INTERVAL @days DAY);
    select @mydate;
    

    然后使用您的插入语句:

    Insert into Loan(... ,[return_date])
    values (...., @mydate)
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2017-11-03
      • 1970-01-01
      • 1970-01-01
      • 2010-10-05
      • 1970-01-01
      • 1970-01-01
      • 2021-02-28
      • 1970-01-01
      • 2020-09-10
      相关资源
      最近更新 更多