简体   繁体   中英

Issues with SQL - SELECT between two dates

I got this old system that I have to do maintenance in the place I work and they asked me to add a Date Filter on the system, but the date field is not only a field, the previous developer has split it in three , just like that " year_id ", " month_id ", " day_id "

And now I have to do a SELECT between the two dates (between the month and year to be more specific) and I tried just like that:

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

When I saw the results I realized that the query is also returning the results from Jan, Feb and Mar of 2018 and it is not supposed to do that. How can I apply those filters?

The ideal thing you should do is add a new column

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

This would create a new column YearMonth and then you can use your filters

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

It should be possible to write a query that implements a date range filtering based on input parameters and on the existing columns. For example if you want records between October 2018 and March 2019 (inclusive), you could do:

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

However the logic need to be adapted depending on the date range. For example if you want records between October 2017 and March 2019, then you need:

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

You can see that this does not scale well. For the sake of simplicity, I would suggest using str_to_date() to convert your strings to date, so you can do proper date comparison:

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

You could add a computed column to your table that prepares the date value for you:

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

Thank everyone that answered && added comments, I just fixed the problem.

The solution posted by GMB worked well, you just saved me <3

I did like u suggested:

$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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM