From 452f41df8da32c87e0170ae033168a694b5032f0 Mon Sep 17 00:00:00 2001 From: zimmi1 Date: Fri, 13 Sep 2013 10:05:30 +0200 Subject: [PATCH] Speeding up sql queries Searching for "DATE_ADD(date_add, INTERVAL 30 MINUTE) > now" needs for every line to add 30 minutes to the date. but it is the same operation as comparing "date_add > (now - 30 minutes). It is faster because there is no DATE_ADD calculation. The problem: By profiling speed of my shop, this query appeared after about 3 months always as the absolute slowest query of the shop, needing about 15 to 30 ms to perform, because I have now nearly 700 connections to my shop (and it then browses the 700 lines) A solution: Removing DATE_ADD MySql function and using date() and time() functions of php for calculating only once the 30 min. difference. Using this solution takes it down again to 0.8 to 1.3 ms. I guess it is the same in case of bots (could be even worse as they can make thousands of connections). --- classes/Connection.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/classes/Connection.php b/classes/Connection.php index 23514695b..206bd307b 100644 --- a/classes/Connection.php +++ b/classes/Connection.php @@ -114,7 +114,7 @@ class ConnectionCore extends ObjectModel // This is a bot and we have to retrieve its connection ID $sql = 'SELECT `id_connections` FROM `'._DB_PREFIX_.'connections` WHERE ip_address = '.ip2long(Tools::getRemoteAddr()).' - AND DATE_ADD(`date_add`, INTERVAL 30 MINUTE) > \''.pSQL(date('Y-m-d H:i:00')).'\' + AND `date_add` > \''.pSQL(date('Y-m-d H:i:00'), time() - 1800).'\' '.Shop::addSqlRestriction(Shop::SHARE_CUSTOMER).' ORDER BY `date_add` DESC'; if ($id_connections = Db::getInstance()->getValue($sql)) @@ -128,7 +128,7 @@ class ConnectionCore extends ObjectModel $sql = 'SELECT `id_guest` FROM `'._DB_PREFIX_.'connections` WHERE `id_guest` = '.(int)$cookie->id_guest.' - AND DATE_ADD(`date_add`, INTERVAL 30 MINUTE) > \''.pSQL(date('Y-m-d H:i:00')).'\' + AND `date_add` > \''.pSQL(date('Y-m-d H:i:00', time() - 1800)).'\' '.Shop::addSqlRestriction(Shop::SHARE_CUSTOMER).' ORDER BY `date_add` DESC'; $result = Db::getInstance()->getRow($sql);