【问题标题】:select mysql data and set value of a variable based on timestamp column根据时间戳列选择mysql数据并设置变量的值
【发布时间】:2016-01-03 08:50:15
【问题描述】:

我需要从表格中选择数据。该表有一个时间戳列。 如果时间戳超过一年,那么我希望该记录的结果为 active=false,否则为 active=true。

我可以只获取结果,然后在 PHP 中循环并设置这个值。但这是否也可以通过某个 MySQL select 语句实现?

下面的答案:

SELECT if(timestamp < now() - interval  1 year,false,true) as active FROM table

【问题讨论】:

    标签: mysql select


    【解决方案1】:

    试试下面的代码,

    UPDATE 'TABLENAME' SET active='false' WHERE timestamp > '1year'
    

    不更新,

    SELECT if(timestamp > '1year',false,true) as flag FROM 'TABLENAME'
    

    【讨论】:

    • 好吧,我不想更新表格。我可以那样做。但我只希望它在 SELECT 语句中......
    • 检查@user1494552。这是你想要的解决方案吗??
    • 检查@user1494552。这是你想要的解决方案吗??
    • 我现在在 SELECT if(now()-edittime > '1day',false,true) as flag FROM table 我想我必须从 now() 中减去它?正确的?您确定“1年”可以识别为1年吗?因为它似乎还没有工作......
    • 不。它无法识别。你必须使用mysql的日期函数。
    【解决方案2】:

    如果您接受一年有 365 天:

    update t
        set active = 0
        where timestampcol < unix_timestamp() - (365*24*60*60);
    

    否则,你需要做一些转换:

    update t
        set active = 0
        where timestampcol < unix_timestamp(date_sub(curdate(), interval 1 year))
    

    【讨论】:

    • 在 Vivek 的回复中查看我的评论。我想知道是否可以仅通过 SELECT 语句。我不想更新表格...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2013-01-10
    • 2014-04-14
    • 2013-01-10
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多