表:id
,status
,time
$now = time(); // current timestamp
$statuses = array (
'ST1' => 60, // (seconds)
'ST2' => 120, // (seconds)
'ST3' => 180, // (seconds)
);
$query = 'SELECT id FROM table WHERE status IN("ST1", "ST2", "ST3") AND time ... LIMIT 1';
现在,我想从表格中选择id
1 row
:
如果status
是ST1 :(时间+60)>现在$
如果status
是ST2 :(时间+ 120)>现在$
如果status
是ST3 :(时间+ 180)>现在$
因此,如果该行具有列status
=“ST1”,则它会检查列time
+ 60是否大于$now
这是当前时间戳,依此类推。
答案 0 :(得分:3)
只需使用基本逻辑:
SELECT l.id
FROM leads l
WHERE ((l.status = 'ST1' and l.time > date_sub(now(), interval 60 second)) or
(l.status = 'ST2' and l.time > date_sub(now(), interval 120 second)) or
(l.status = 'ST3' and l.time > date_sub(now(), interval 180 second))
)
LIMIT 1;
我假设(time + xx) > $now
指的是秒。此外,我鼓励您使用数据库时间,而不是传入它。(当然,您可以将now()
替换为$now
- 或者更好的参数 - 如果您有充分的理由从申请中抽出时间。)
老实说,我可能会把它放在派生表中:
SELECT l.id
FROM leads l JOIN
(SELECT 'ST1' as status, 60 as diff UNION ALL
SELECT 'ST2' as status, 120 as diff UNION ALL
SELECT 'ST3' as status, 180 as diff
) s
ON l.status = s.status
WHERE l.time > date_sub(now(), interval s.diff second)
LIMIT 1;
答案 1 :(得分:2)
使用CASE
声明:
SELECT id FROM table WHERE
CASE
WHEN status="ST1" THEN (time + INTERVAL 60 SECOND) > NOW()
WHEN status="ST2" THEN (time + INTERVAL 120 SECOND) > NOW()
WHEN status="ST3" THEN (time + INTERVAL 180 SECOND) > NOW()
END CASE