我必须向最终用户显示系统状态: 所以我有一组查询,以1min,5min,hour,day,month间隔显示发送的数据
$sentCount = new stdClass();
$sentCount->amon = $link->query("select * from row_sent where result='succes' and TIMESTAMPDIFF(SECOND, send_date , now()) < 2073600 ;")->num_rows;
$sentCount->amin = $link->query("select * from row_sent where result='succes' and TIMESTAMPDIFF(SECOND, send_date , now()) < 60 ;")->num_rows;
$sentCount->a5min = $link->query("select * from row_sent where result='succes' and TIMESTAMPDIFF(SECOND, send_date , now()) < 300 ;")->num_rows;
$sentCount->ahour = $link->query("select * from row_sent where result='succes' and TIMESTAMPDIFF(SECOND, send_date , now()) < 3600 ;")->num_rows;
$sentCount->aday = $link->query("select * from row_sent where result='succes' and TIMESTAMPDIFF(SECOND, send_date , now()) < 86400 ;")->num_rows;
但是这种风格的代码需要大量时间才能执行 我如何更改它以获得更快的答案!?
答案 0 :(得分:1)
似乎您只需要行计数。您当前代码的问题如下:
尝试以下查询:
$sentCount = new stdClass();
$sentCount->amon = $link->query("select COUNT(*) as count from row_sent where result='succes' and TIMESTAMPDIFF(SECOND, send_date , now()) < 2073600 ;")->row['count'];
$sentCount->amin = $link->query("select COUNT(*) as count from row_sent where result='succes' and TIMESTAMPDIFF(SECOND, send_date , now()) < 60 ;")->row['count'];
$sentCount->a5min = $link->query("select COUNT(*) as count from row_sent where result='succes' and TIMESTAMPDIFF(SECOND, send_date , now()) < 300 ;")->row['count'];
$sentCount->ahour = $link->query("select COUNT(*) as count from row_sent where result='succes' and TIMESTAMPDIFF(SECOND, send_date , now()) < 3600 ;")->row['count'];
$sentCount->aday = $link->query("select COUNT(*) as count from row_sent where result='succes' and TIMESTAMPDIFF(SECOND, send_date , now()) < 86400 ;")->row['count'];
答案 1 :(得分:0)
首先,您可以组合成一个查询,并使用IF
和SUM
来获得结果。
SELECT
*,
SUM(IF(TIMESTAMPDIFF(SECOND, send_date, NOW()) < 2073600,1,0)) AS MONTH,
SUM(IF(TIMESTAMPDIFF(SECOND, send_date, NOW()) < 60,1,0)) AS one_min,
SUM(IF(TIMESTAMPDIFF(SECOND, send_date, NOW()) < 300,1,0)) AS five_min,
SUM(IF(TIMESTAMPDIFF(SECOND, send_date, NOW()) < 3600,1,0)) AS HOUR,
SUM(IF(TIMESTAMPDIFF(SECOND, send_date, NOW()) < 86400,1,0)) AS DAY
FROM
row_sent
WHERE
result = 'succes';