【问题标题】:How can I insert date range in mysql database using query?如何使用查询在 mysql 数据库中插入日期范围?
【发布时间】:2022-01-03 17:06:45
【问题描述】:

例如,我在数据库表中有一个名为 date 的字段,我想插入表中的日期范围为 2021-11-25 到 2021-11-30。 我不知道如何编写查询以在新行中的每个日期将日期插入数据库。 像这样:

  1. 2021-11-25
  2. 2021-11-26
  3. 2021-11-27
  4. 2021-11-28
  5. 2021-11-29
  6. 2021-11-30

感谢您的帮助...

【问题讨论】:

  • 您想通过 SQL 还是通过 JPA 进行插入?

标签: java mysql spring-boot spring-data-jpa


【解决方案1】:

如何编写查询以在新行中的每个日期向数据库中插入日期。

好的,鉴于该问题带有 JPA 标记,我将为您提供 JPA 答案。

你创建一个像...这样的实体

@Entity
class MyEntity {
  @Id
  @GeneratedValue
  Long id;
  DateTime myDate
}

然后你可以像这样创建一个数据范围列表..

 public static List<DateTime> getDateRange(DateTime start, DateTime end) {

        List<DateTime> ret = new ArrayList<DateTime>();
        DateTime tmp = start;
        while(tmp.isBefore(end) || tmp.equals(end)) {
            ret.add(tmp);
            tmp = tmp.plusDays(1);
        }
        return ret;
    }

然后您从此列表中创建实体并使用存储库类插入它们。

这能解决你的问题吗?

【讨论】:

    【解决方案2】:

    首先,您必须通过定义一个简单的方法来生成数据:

    public List<LocalDate> dateRange(LocalDate from, LocalDate to) {
       return from.datesUntil(to).collect(Collectors.toList());
    }
    

    然后,您可以以自己喜欢的方式存储数据。

    以 Spring Data JPA 为例:

    // Your Entity
    @Entity
    public class DateEntity {
    
      public DateEntity(LocalDate localDate) {
         this.localDate = localDate;
      }
    
      @Id
      @GeneratedValue
      private Long id;
      private LocalDate localDate;
    }
    
    // Your Repository
    @Repository
    public interface DateEntityRepository extends JpaRepository<DateEntity, Long> {
    }
    
    // And the glue
    List<DateEntity> dateEntities = dateRange(from, to).stream()
           .map(localDate -> new DateEntity(localDate))
           .collect(Collectors.toList());
    
    dateEntityRepository.saveAll(dateEntities);
    
    

    【讨论】:

      【解决方案3】:

      您可以使用这样的查询。

      插入 table_name (.... , date_field) 值 选择 .... , selected_date from (select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from (选择0 我并集选择1 并集选择2 并集选择3 并集选择4 并集选择5 并集选择6 并集选择7 并集选择8 并集选择9)t0, (选择 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, (选择 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, (选择0我并集选择1并集选择2并集选择3并集选择4并集选择5并集选择6并集选择7并集选择8并集选择9)t3, (选择 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 其中 selected_date 在“2012-02-10”和“2012-02-15”之间

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-10
        • 2012-09-14
        • 1970-01-01
        • 2014-01-07
        • 2011-01-01
        • 1970-01-01
        • 2020-07-08
        相关资源
        最近更新 更多