【问题标题】:If statement in where clause in mysql select statementmysql select语句中where子句中的if语句
【发布时间】:2018-04-09 14:04:08
【问题描述】:

我需要在我的 select 语句的 where 子句中添加一个“if”。我正在搜索两个日期,并想在两个日期之间提取数据。我需要检查年份是否不同,月份是否不同,然后是日期。我当前的选择语句是:

  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'

目前,如果开始日期和结束日期的年份和月份相同,则该语句有效。但是,当月份/年份不同时,它无法正常工作。如果我输入 2018-3-1 和 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

请你告诉我如何做一个 if 语句,如果月份和年份不同,它将搜索该月的剩余时间。

对不起,如果这是一个简单的问题。

谢谢

【问题讨论】:

  • where 子句基本上是一个if 语句:“在结果中包含一行...”。您如何看待“搜索本月剩余时间”这件事?
  • 你的问题毫无意义。您指定一个包含一列的查询,但“返回的数据”有 7 列。我建议你问另一个问题。请务必包含示例数据、期望的结果以及对您想要完成的目标的良好解释。

标签: mysql sql database stored-procedures


【解决方案1】:

IF 语句只能用在过程语法中,不能用在where 子句的查询语句中。尽管您可以根据需要使用CASE 语句。此外,不要认为您当前的方法有任何问题

【讨论】:

    猜你喜欢
    • 2012-10-11
    • 2021-07-17
    • 2010-12-07
    • 2016-12-29
    • 2013-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    相关资源
    最近更新 更多