用条件计算mySQL中的时间差

时间:2017-01-30 12:22:05

标签: mysql sql

我有这个查询必须选择 1行,其中status是“OKQ”,“PI”,“CBK”,“NRP”,“新”,如果“ OKQ“,(status_time + 86400)必须 SMALLER 而不是 NOW 这是当前时间戳,因此在执行查询时,状态必须已经在过去中的status_time + 86400秒,依此类推,如查询中所述:

SELECT id FROM leads t JOIN (
    SELECT "OKQ" as status, 86400 as diff UNION ALL
    SELECT "PI" as status, 3600 as diff UNION ALL
    SELECT "CBK" as status, 60 as diff UNION ALL
    SELECT "NRP" as status, 3600 as diff UNION ALL
    SELECT "NEW" as status, 1 as diff
) s USING (status)
WHERE t.status_time > date_sub(now(), interval s.diff second)
ORDER BY RAND()
LIMIT 1

现在此查询会将0作为num_rows返回,尽管其中大部分记录为“新”,而“新”的status_time为4天,因此{{1} (当前时间戳)远远大于4天前+ 1秒,因此必须选择一行。

1 个答案:

答案 0 :(得分:1)

您的查询应如下所示,您应该使用<而不是>

SELECT id FROM lead t JOIN(     选择“OKQ”作为状态,选择86400作为diff UNION ALL     选择“PI”作为状态,3600作为diff UNION ALL     选择“CBK”作为状态,60作为diff UNION ALL     选择“NRP”作为状态,将3600作为diff UNION ALL     选择“NEW”作为状态,选择1作为diff )s USING(状态) 在哪里t.status_time< date_sub(now(),interval s.diff second) 兰德令() 限制1