【问题标题】:Insert every date of the year mysql [closed]插入一年中的每个日期mysql [关闭]
【发布时间】:2017-01-27 06:56:15
【问题描述】:

我想将一年中的每个日期添加到我的数据库表中。我怎么能这样做?

我在谷歌上找,但没有任何线索。

请帮助我完成一些插入查询。

这是我的表结构。

id | date
---------
1 | 2017-01-01

【问题讨论】:

标签: mysql


【解决方案1】:

问题澄清后更新。

这是一个更新的版本,试试这个。要使 while 循环正常工作,您需要将其创建为存储过程。像这样创建存储过程

DELIMITER $$

create PROCEDURE insert_year_dates() 
BEGIN 
    SET @t_current = NOW(); 
    SET @t_end = DATE_ADD(NOW(), INTERVAL 1 YEAR); 
    WHILE(@t_current< @t_end) DO 
        INSERT INTO day (day) VALUES (@t_current); 
        SET @t_current = DATE_ADD(@t_current, INTERVAL 1 DAY); 
    END WHILE; 
END; 

然后使用

调用该存储过程
CALL insert_year_dates()

【讨论】:

  • 你能给我完整的插入查询吗?我想要这样的日期格式yyyy-mm-dd
  • 我已经更新了答案,但正如我所说,不知道你的表结构是什么我不能给你一个准确的查询。
  • 我刚刚用表格结构编辑了我的问题,它只是用字段iddate 简化表格
  • 接受我的回答并将table 替换为您的表名,并将field 替换为您的字段名。
  • 您确定DATE_ADD(NOW(), YEAR, 1) 有效吗?我只知道DATE_ADD(NOW(), INTERVAL 1 YEAR)
【解决方案2】:

您可以先尝试获取当前日期之间的所有日期并添加它。

insert into day (date)
    select * from 
    (select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
     (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
     (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
     (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
     (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
     (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
    where selected_date between '2017-01-01' and '2017-12-31'

【讨论】:

  • 我收到了这个错误You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'as select * from (select adddate('1970-01-01',t4.i*10000 + t3.i*1000' at line 1
  • 哦删除 as。立即查看
  • 你能帮我解决这个问题吗Resul query with if condition
  • 我无法理解您的 if 条件。所以首先把所有可能值 0 和 1 的表放在表中。并显示日期的 imp 是什么
  • 我刚刚编辑了我的问题,请看一下。
【解决方案3】:

在 mysql 中,您可以选择仅使用日期格式填充的列。您可以将数据插入为“2017”或“17”。两者都可以正常工作。

【讨论】:

    猜你喜欢
    • 2019-04-02
    • 2014-12-31
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    相关资源
    最近更新 更多