dtvfxzq3802 2015-07-27 20:56
浏览 37
已采纳

改进MySQL查询:计算行数

I have the following query where it takes minutes to load, when actually I need only to count how many rows it returns. I would like to know if is it possible to improve this query?

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;

This is my code:

$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条回答 默认 最新

  • dsbo44836129 2015-07-27 21:55
    关注

    try this:

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

    (clock - clock mod 300) should be the same value as clock div 300, but likely with less overhead; mod ops typically some of the more expensive operations, since they are usually implemented as x-(x*(x div y)). Since you only want the number of rows returned, you only need the number of values that would've been grouped on; hence the COUNT(DISTINCT); and as @ssnobody pointed out above, x <= y && x >= y indicates x==y.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器