合并查询以获得最快的答案

时间:2018-09-27 07:36:28

标签: mysql mysqli

我必须向最终用户显示系统状态: 所以我有一组查询,以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;

但是这种风格的代码需要大量时间才能执行 我如何更改它以获得更快的答案!?

2 个答案:

答案 0 :(得分:1)

似乎您只需要行计数。您当前代码的问题如下:

  • 如果只想获取行数,则应使用内置的COUNT()函数。这样会更快。
  • 第二,现在从数据库服务器到应用程序代码的数据包变得越来越小。您不是要获取所有行数据,而是现在只有一个数字。
  • 另外,请阅读Why is SELECT * considered harmful?

尝试以下查询:

$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)

首先,您可以组合成一个查询,并使用IFSUM来获得结果。

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';