改进MySQL查询:计算行数

时间:2015-07-27 20:56:53

标签: php mysql select count

我有以下查询,其中加载需要几分钟,实际上我只需要计算它返回的行数。我想知道是否可以改进此查询?

SELECT (clock - clock mod 300) as time, avg(value) as value FROM table.history_uint WHERE itemid = 82660 AND clock >= UNIX_TIMESTAMP('".$date."') AND clock <= UNIX_TIMESTAMP('".$date."') GROUP BY time;

这是我的代码:

$queryPageInfo = "SELECT (clock - clock mod 300) as time, avg(value) as value FROM table.history_uint WHERE itemid = 82660 AND clock >= UNIX_TIMESTAMP('".$date."') AND clock <= UNIX_TIMESTAMP('".$date."') GROUP BY time";
$resultPageInfo = $mysqli->query($queryPageInfo);
$qtd = $resultPageInfo->num_rows;

1 个答案:

答案 0 :(得分:2)

试试这个:

SELECT COUNT(DISTINCT clock DIV 300)
FROM table.history_uint 
WHERE itemid = 82660 AND clock = UNIX_TIMESTAMP('".$date."')
;

(clock - clock mod 300)应与clock div 300具有相同的值,但可能会减少开销; mod ops通常是一些更昂贵的操作,因为它们通常实现为x-(x *(x div y))。由于您只想要返回的行数,因此您只需要分组的值的数量;因此COUNT(DISTINCT);正如@ssnobody指出的那样,x&lt; = y&amp;&amp; x> = y表示x == y。