简体   繁体   中英

If statement in where clause in mysql select statement

I need to put an 'if' into my where clause in my select statement. I am searching through two dates and want to pull the data between the two of them. I need to check if the year is different, if the month is different and then the day. my current select statement is:

  select count(*)
  from SOMT_Development.Board_Metrics_Data bmd
  where bmd.Metric_Year >= startYear and bmd.Metric_Year <= endYear and 
  Metric_Month >= startMonth and Metric_Month <= endMonth and 
  bmd.Metric_Day >= startDay and bmd.Metric_Day <= endDay and 
  bmd.Board_Metrics_ID = 1 and bmd.Value_Colour = "Red" and
  bmd.Date_Created = (select max(bmd2.Date_Created)
                  from SOMT_Development.Board_Metrics_Data bmd2
                  where bmd2.Board_Metrics_ID = bmd.Board_Metrics_ID and
                        bmd2.Metric_Year = bmd.Metric_Year and
                        bmd2.Metric_Month = bmd.Metric_Month and
                        bmd2.Metric_Day = bmd.Metric_Day
                 )) as 'red'

Currently if the year and month are the same in both start and end date the statement works. However when the months/years are different it does not work correctly. This is the data that comes back if I input the dates for 2018-3-1 and 2018-4-4

  2018-03-29 09:46:20    green   1   no_comment  2018    3   1
  2018-03-29 09:46:20    red     1   no_comment  2018    3   2
  2018-03-29 09:46:20    white   1   no_comment  2018    3   3
  2018-03-29 09:46:20    white   1   no_comment  2018    3   4
  2018-04-04 13:25:19    green   1   no_comment  2018    4   4
  2018-04-02 13:25:30    green   1   no_comment  2018    4   2
  2018-04-03 13:25:47    green   1   no_comment  2018    4   3

Please could you show me how to do an if statement that, if the months and years are different, would search through the rest of the month.

Sorry if this is a simple question.

Thanks

IF statement can only be used in procedural syntax and not in a query statement in where clause. Though you can use CASE statement if needed be. Moreover, don't see anything wrong with your current approach

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