我可以在MySQL中计算DateTime范围吗?

I currently calculate the difference in time to retrieve a list of active users liek so:

$timeout = 300;
$time = strtotime("-{$timeout} sec");
$time_str = date("Y-m-d H:i:s", $time);

$SQL = "SELECT COUNT(*) AS users FROM active_users WHERE user_id={$user_id} AND last_time >= '{$time_str}'";

Can this time diff be done in a MySQL query directly? If so is there any performance impact?

SELECT ... AND last_time >= (NOW() - INTERVAL $timeout SEC)

Performance impact is... unknown. Depends on how efficient PHP v.s. MySQL's date/time manipulation code is. Probably come out about the same, since they're both probably using the same underlying libc/glibc functions anyways.

Yes it can be done in the MySQL directly and in some cases might be preferable if you have different timezones between web server and MySQL server or the clocks between application server and database server are not correctly synchronized. My personal preference is to treat the database-derived times (i.e timestamps) as authoritative and thus would recommend the MySQL approach. The query might look like this:

SELECT COUNT(*) AS users FROM active_users WHERE user_id={$user_id} AND last_time >= DATE_SUB(NOW(), INTERVAL {$timeout} SECONDS)