Doubt in SQL query "between" or "in"

1

I am generating a report between date, as shown below:

However,whenIenterthestartdate:

Startingyear:2014Startmonth:6and

FinalYear:2015FinalMonth:5

IfIusetheINclausethequeryreturnsonlymonths6and5andnotreturningmonth4,butwhenusedBETWEENdoesnotreturnanydata.

Followthequery.

BETWEEN

WHEREv.verba_anoBETWEEN$anoAND$ano_fnalANDv.verba_mesBETWEEN$mesAND$mes_fim

IN

$WHERE="WHERE v.verba_ano IN($ano,$ano_fnal) AND v.verba_mes IN($mes,$mes_fim)";
    
asked by anonymous 18.06.2015 / 14:54

5 answers

2

Do this (if it's php and mysql)

WHERE STR_TO_DATE(CONCAT_WS('-', v.verba_ano, v.verba_mes), "%Y-%m") BETWEEN STR_TO_DATE('{$ano}-{$mes}', "%Y-%m") AND STR_TO_DATE('{$ano_fim}-{$mes_fim}', "%Y-%m")
    
18.06.2015 / 21:34
2

The BETWEEN expects the first parameter to be less than the second, which causes its problem.

Using IN also does not solve your problem because it does not work with ranges, but with isolated values. Ex: data IN (3,8) will not bring the range 3 to 8, but rather exactly values 3 and 8

Solution

Change your query to select the complete date, in AAAA-MM-DD format.

Always try to store date columns with type DATE in your database.

The day you can dynamically generate from the query:

SELECT * FROM tabA
WHERE verba_data BETWEEN '{$ano}-{$mes}-01' AND last_day('{$ano_fnal}-{$mes_fim}-01');

Here's an example in sqlfiddle .

    
18.06.2015 / 15:13
1

Try something like that, it worked for me.

WHERE (v.verba_ano BETWEEN $ano AND $ano_fnal) AND (v.verba_mes BETWEEN $mes AND $mes_fim)
    
18.06.2015 / 15:15
1

Compare dates is easy if you reverse month / year to year / month in a single integer value: In your example 06/2014 to 05/2015 you would compare if the date is between 201406 and 201505.

where (verba_ano * 100 + verba_mes) between 201406 and 201505

Where 201406 = $ year * 100 + $ month and 201505 - $ year_fin * 100 + $ month_fin

If you need the day, the formula is also

ano * 10000 + mes * 100 + dia
    
18.06.2015 / 20:29
0

It worked right here, follow the code below:

AND STR_TO_DATE(CONCAT_WS('-',i.func_ano,i.func_mes,'01'),'%Y-%m-%d')
BETWEEN STR_TO_DATE('$ano-$mes-01','%Y-%m-%d') 
AND STR_TO_DATE('$ano_fnal-$mes_fim-01','%Y-%m-%d')
    
18.06.2015 / 21:53