【问题标题】:Issues with SQL - SELECT between two datesSQL 问题 - 两个日期之间的 SELECT
【发布时间】:2020-04-02 20:06:07
【问题描述】:

我得到了这个旧系统,我必须在我工作的地方进行维护,他们要求我在系统上添加一个日期过滤器,但是日期字段不仅仅是一个字段,之前的开发人员已经将它拆分为 三个,就像“year_id”、“month_id”、“day_id

现在我必须在两个日期之间进行 SELECT(更具体地说,是在 monthyear 之间),然后我就这样尝试了:

select 
    * from `table` 
where 
    ( 
        (`year_id` >= 2018 and `month_id` >= 10) 
    or 
        (`year_id` <= 2019 and `month_id` <= 3) 
    ) 

当我看到结果时,我意识到查询还返回了 2018 年 1 月、2 月和 3 月的结果,它不应该这样做。 如何应用这些过滤器?

【问题讨论】:

  • 您尝试过这种格式吗? : "SELECT * FROM TABLE where startdate = '$enddate'"
  • 即使有解决此问题的方法,我还是建议您在表中添加一个新列,其中包含一个包含 3 列内爆值的日期字段。这将帮助您轻松过滤
  • 更具体一些 - 如果您不希望 2019 年之前的年份用于第二个子句,请不要使用 &lt;=
  • 如果你仔细观察,这个标准表明任何year &lt; 2019month 1,2,3 都是候选对象,所以每年都小于2019。(year_id` month_id (year_id` >= 2018 和 month_id >= 10)`,则此标准也适用于 EVERY year > 2018`
  • 为什么不简单地修复你的模型?

标签: php mysql sql laravel select


【解决方案1】:

理想的做法是添加一个新列

select 
    *,STR_TO_DATE(Concat(year_id,month_id),'%Y%m') as 'YearMonth' from `table`;

这将创建一个新列YearMonth,然后您可以使用您的过滤器

select * from (
select 
        *,STR_TO_DATE(Concat(year_id,month_id),'%Y%m') as 'YearMonth' from `table`
) z where (YearMonth between '201810' and '201903')

【讨论】:

    【解决方案2】:

    应该可以编写一个查询来实现基于输入参数和现有列的日期范围过滤。例如,如果您想要 2018 年 10 月至 2019 年 3 月(含)之间的记录,您可以这样做:

    (year_id = 2018 and month_id >= 10)
    or (year_id = 2019 and month_id <= 3)
    

    但是,需要根据日期范围调整逻辑。例如,如果您想要 2017 年 10 月到 2019 年 3 月之间的记录,那么您需要:

    (year_id = 2017 and month_id >= 10)
    or year_id = 2018
    or (year_id = 2019 and month_id <= 3)
    

    您可以看到这不能很好地扩展。为了简单起见,我建议使用str_to_date() 将您的字符串转换为日期,以便您可以进行适当的日期比较:

    str_to_date(concat (year_id, '-', month_id), '%Y-%m') between '2017-10-01' and '2019-03-01'
    

    您可以在表中添加一个计算列,为您准备日期值:

    alter table mytable add 
        mydate date as (str_to_date(concat (year_id, '-', month_id), '%Y-%m'))
    

    【讨论】:

      【解决方案3】:

      感谢所有回答&&添加cmets的人,我刚刚解决了这个问题。

      GMB 发布的解决方案效果很好,你刚刚救了我

      我确实像你建议的那样:

      $data_inicial = Controller::toDate($data_inicial, 'm/Y', 'Y-m') . '-01';
      $data_final = Controller::toDate($data_final, 'm/Y', 'Y-m') . '-01';
      $query->whereBetween(DB::raw("STR_TO_DATE(CONCAT(sicc_ano_id, '-', sicc_mes_id), '%Y-%m')"), [$data_inicial, $data_final]);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-24
        • 2015-06-21
        • 2021-11-28
        • 2021-08-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多