MYSQL PHP查询耗时过长

时间:2017-08-06 14:53:45

标签: php mysql

我有一个简单的问题或问题,我无法为我的生活得到。我在PHP中有一个MYSQL查询,但它需要永远加载看似它正在访问的数据库拥有多行1000多个。使用下面的当前脚本,它在大约25秒内加载,并且有6,000行。

$SQLGetUsers = $odb -> query("SELECT m.id,m.userid,m.btc,m.unpaidbtc,m.addedbtc,m.ltc,m.unpaidltc,m.addedltc,m.totalbtcmined,m.totalltcmined,u.totalbtcreward,u.totalltcreward, SUM(r.totalbtcdeposited) AS value_sum1, SUM(r.totalltcdeposited) AS value_sum2 
  FROM miner m 
  LEFT JOIN users u ON m.userid = u.ID
  LEFT JOIN referrals r ON m.userid = r.refid ");

while ($getInfo = $SQLGetUsers -> fetch(PDO::FETCH_ASSOC))
{
  $ID = $getInfo['id'];
  $userid = $getInfo['userid'];
  $totalbtc = $getInfo['btc'];
  $totalunpaidbtc = $getInfo['unpaidbtc'];
  $addedbtc = $getInfo['addedbtc'];
  $totalltc = $getInfo['ltc'];
  $totalunpaidltc = $getInfo['unpaidltc'];
  $addedltc = $getInfo['addedltc'];
  $totalbtcmined = $getInfo['totalbtcmined'];
  $totalltcmined = $getInfo['totalltcmined'];

  ///////////////////////////////////////////////

    $newBTCbalance = ($totalbtc);

    $btctoadd = number_format($newBTCbalance / 45 / 24 / 60 / 60 * 3, 10);
    $newbtcvalue = $totalunpaidbtc + $btctoadd;
    $odb->exec("UPDATE miner SET addedbtc = '$btctoadd', unpaidbtc = '$newbtcvalue' WHERE `id` = '$ID'");

    $newLTCbalance = ($totalltc);

    $ltctoadd = number_format($newLTCbalance / 45 / 24 / 60 / 60 * 3, 10);
    $newltcvalue = $totalunpaidltc + $ltctoadd;
    $odb->exec("UPDATE miner SET addedltc = '$ltctoadd', unpaidltc = '$newltcvalue' WHERE `id` = '$ID'");

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  $minedbtc = $btctoadd + $totalbtcmined;
  $minedltc = $ltctoadd + $totalltcmined;
  $odb->exec("UPDATE miner SET totalbtcmined = '$minedbtc', totalltcmined = '$minedltc' WHERE `id` = '$ID'");
}

我不知道如何才能加快查询速度,使其在不到1秒的时间内运行,甚至是可能的?好吧无论如何,任何人都可以帮助让这个更快地运行?

1 个答案:

答案 0 :(得分:0)

解决此问题的最佳方法是使用LIMIT子句。

https://dev.mysql.com/doc/refman/5.7/en/limit-optimization.html

假设您有一个查询列出所有博客文章,并且您有超过10k的帖子,查询将需要很长时间才能执行。通常人们使用LIMIT子句从MySQL数据库中获取一定数量的数据并创建分页。

实施例

$query = $query->query("SELECT * FROM data LIMIT 10"); // Only get 10 data from query

$query = $query->query("SELECT * FROM data LIMIT 10 OFFSET 10"); // The data from index 9 will be retrived make the OFFSET value dynamic