表:id
,状态
,时间
$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
of 1 row
,其中:
如果 status
是 ST1:(time + 60) > $now
如果 status
是 ST2: (time + 120) > $now
如果 status
是 ST3:(time + 180) > $now
因此,如果该行的列 status
= "ST1",它会检查列 time
+ 60 是否大于 $now
这是当前时间戳,依此类推。
最佳答案
只需使用基本逻辑:
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;
关于mySQL 条件选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41909832/