mysql - mysql select语句中where子句中的if语句

标签 mysql sql database stored-procedures

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

  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 语句,如果月份和年份不同,则将搜索该月的剩余时间。

抱歉,如果这是一个简单的问题。

谢谢

最佳答案

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

关于mysql - mysql select语句中where子句中的if语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49734904/

相关文章:

database - 我如何在播放框架中使用默认数据库以外的其他数据库?

mysql - 用破折号替换空格并复制到新列中

php - Mysql计数不删除

php - 我的 php 测验应用程序在插入问题时无法正常工作

MySQL: `REFERENCES` 与 `FOREIGN KEY` + `REFERENCES`

sql - 如何从命令行调用 Oracle SQL 过程?

sql - 多级级联内连接选择查询

c# - 在 visual studio 中查看 .mdf 文件的数据

mysql - 在 mysql 导入期间隐藏错误

php - 在 Shell 脚本中创建数据库 - 从 PHP 转换