【问题标题】:How to tell if an SQL date is still in the future (not a query, I already have the desired row)如何判断 SQL 日期是否仍在未来(不是查询,我已经有了所需的行)
【发布时间】:2012-05-06 19:30:05
【问题描述】:

我有一个 SQL 表中的一行,其中一个字段是 DATE。 (该值可能未定义,因为 DATE 没有默认值)。我如何判断这个日期(如果存在)是否还在未来?

我搜索了答案并找到了很多方法来提取通过此测试的所有记录,但我不想这样做。我只想检查这个先前提取的记录。抱歉新手问题!

$userQuery  = "SELECT * FROM  `passwords` WHERE `name` = '$name' LIMIT 1";
$userResult     = mysql_query($userQuery);    
$userRow        = mysql_fetch_assoc($userResult); 
$bestBeforeDate = $userRow['bestBeforeDate']; // field is in DATE format
// what now? How to find if the 'best Before Date' has passed?

【问题讨论】:

    标签: sql date compare


    【解决方案1】:

    您可以在 SQL 中将其作为附加列进行

    select case when (current_timestamp < date_column) 
                then 1
                else 0
                end as is_in_future
    from your_table
    

    编辑

    您可以在一个查询中执行此操作,同时从表中读取其他值。
    示例(不知道表的列名)

    select id,
           date_column,
           other_column,
           case when (current_timestamp < date_column) 
                then 1
                else 0
           end as is_in_future
    from your_table
    where some_conditions
    

    示例输出:

    id  date_column   other_column   is_in_future
     1  2012-01-01    abc            0
     2  2012-08-01    def            1
     ...
    

    【讨论】:

    • 这是从原始表中选择的吗?有许多记录满足该查询,但我只想检查我已经提取的记录。
    • @ChrisTolworthy:您可以将其添加到从数据库中提取bestBeforeDate 的查询中。
    • 谢谢。我还需要从该记录中读取其他变量,无论它是否通过日期测试。听起来我只需要进行两个不同的查询? IE。查询表一次以获取记录并检查其日期,然后再次查询表以获取相同的记录,无论日期如何?
    猜你喜欢
    • 2014-04-29
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    • 2020-05-31
    • 2014-05-11
    • 2012-05-19
    • 1970-01-01
    相关资源
    最近更新 更多