【问题标题】:Mysql Query : Where clause if ExistsMysql 查询:如果存在 Where 子句
【发布时间】:2009-05-06 05:50:42
【问题描述】:

我有一个 MySQL 数据库,其中有一个名为 ProductMaster 的表,其中包含 6 个字段“Product_Id、Product_Name、Model、Opening_date、Closing_Date、Status”。 Opening_Date 和 Closing Date 可以接受空值。所以有些记录有这个字段的值

我有以下查询来显示该表中的记录。

"select Product_Id,Product_Name,Model from ProductMaster  where Status=1"

现在我想更改查询以对 Opening_Date 和 Closing_Date 进行过滤 如果它们不为空

例如:如果记录的 Opening_Date 为 05/01/2009,Closing Date 为 05/30/2009 然后我想检查今天是否是这两个日期之间的日期,如果是,则返回记录

如果两个字段值都为空,则返回记录

任何人都可以帮助我构建查询吗?提前致谢

【问题讨论】:

  • 您能否说明是否应返回 opening_date 和 closing_date 设置为 null 的记录?

标签: mysql exists


【解决方案1】:

查询的WHERE 部分(“WHERE 子句”)只是一个长布尔表达式。这是什么意思? MySQL 只是希望它返回 true 或 false,它理解为“是的。在结果中包含这一行。”或“不。不要在结果中包含这一行。”

如果我理解正确,你想做两件事:

  1. 检查opening_dateclosing_date是否为null
  2. 检查今天是否在这两个日期之间。

并且您希望 #2 仅在 #1 为真时发生。可以这样表达:

#1 AND #2

如果 #1 或 #2 为假,则将被评估为假。

可以翻译为:

  1. (opening_date IS NOT NULL) AND (closing_date IS NOT NULL)
  2. NOW() >= opening_date AND NOW <= closing_date

因此,如果我们将这两个视为我们将要使用的表达式中的 #1 和 #2 (#1 AND #2),那么我们会得到:

((opening_date IS NOT NULL) AND (closing_date IS NOT NULL)) 
AND (NOW() >= opening_date AND NOW <= closing_date`)

这就是您需要的WHERE 子句。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2020-10-13
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    相关资源
    最近更新 更多