How to filter separate dates by day , month and year in Mysql

Asked

Viewed 1,251 times

6

Hello, I have a table "Meetings" in Mysql with the following structure:

id:Int(11), subject:String(40), day:String(2), mes:String(2), year:String(4), active:String(2)

except in the field day the day of the meeting, month the corresponding number of the month of the meeting, and in year, the year that it occurs. for example: an A meeting that takes place on 20/04/2015 day = 20 mes = 04 year = 2015

would like to sort the result by proximity of the meeting, ie the one that is closer to occur first. for this I used the following sql:

SELECT * FROM Reuniao ORDER BY ano ASC, mes ASC, dia ASC

worked, but it also shows the meetings if they have already passed (first), but I need you to show only the ones that will still happen. then I tried the following:

SELECT * FROM Reuniao WHERE ano >= 2015 AND mes >= 3 AND dia >= 3 ORDER BY ano ASC, mes ASC, dia ASC

Assuming that today was 03/03/2015 she should show all meetings that take place from now on, but presents an error, shows no meetings any meeting that takes place before the 3rd of any month, and the 3rd of any year.

how to solve this? and also show only those that activates = "S"

1 answer

6


The problems are :

1) Compare string with number

2) year >= 2015 AND mes >= 3 AND day >= 3 , considering that both are integer is incorrect pq for example if we have the values (2016 , 2 , 3) even the year being bigger , as the month is smaller the condition will fail .

And a solution:

Convert separate fields to Date

     SELECT * FROM Reuniao
     WHERE str_to_date(concat_ws(',',dia,mes,ano),'%d,%m,%Y') >= curdate() AND ATIVA = 'S'
     ORDER BY ano ASC, mes ASC, dia ASC

Supplementing with the question of taking into account the time you can do so:

To use a string with the time in str_to_date you only need to specify the format !

For example with fomarto hh:mm

     str_to_date(concat_ws(',',hora,dia,mes,ano),'%H:%i,%d,%m,%Y') 
  • 1

    Thank you, it worked! but I have a doubt, in the function str_to_date, there in concat_ws where you have ',' before day, would be the time? if I had a time field in the 22:00 format I could do so: str_to_date(concat_ws(hora,dia,mes,ano)? @Johndiego

  • @Athilazuma vo put in the answer !

  • My time is in the format 24h and this accepts only 12h, I can convert it in my program but still need to know how to indicate there in str_to_date the AM/PM. or how to use in 24h format. @Johndiego

  • @Athilazuma uses %H instead of %h , I edited the answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.