From 9f8876a9fcfd72f55be4076a95507d704bba101b Mon Sep 17 00:00:00 2001 From: Emil Zhai Date: Wed, 30 Nov 2022 06:39:30 +0000 Subject: [PATCH] feat: optimize sql performance while get all count, #69 --- Access_Statistic.php | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/Access_Statistic.php b/Access_Statistic.php index ab4a0fa..30d5025 100644 --- a/Access_Statistic.php +++ b/Access_Statistic.php @@ -6,7 +6,7 @@ if (!defined('__ACCESS_PLUGIN_ROOT__')) { class Access_Statistic { private $db; private $request; - + public function __construct($request) { $this->db = Typecho_Db::get(); $this->request = $request; @@ -27,7 +27,7 @@ class Access_Statistic { # 总计数据 case 'total': $startTime = 0; - $endTime = time(); + $endTime = 0; break; # 按天统计 case 'day': @@ -53,8 +53,10 @@ class Access_Statistic { # ip数 $subQuery = $this->db ->select('DISTINCT ip') - ->from('table.access_log') - ->where("time >= ? AND time <= ?", $startTime, $endTime); + ->from('table.access_log'); + if ($endTime > 0) { + $subQuery->where("time >= ? AND time <= ?", $startTime, $endTime); + } if(method_exists($subQuery, 'prepare')) $subQuery = $subQuery->prepare($subQuery); $resp['count']['ip'] = intval($this->db->fetchRow( @@ -65,8 +67,10 @@ class Access_Statistic { # 访客数 $subQuery = $this->db ->select('DISTINCT ip, ua') - ->from('table.access_log') - ->where("time >= ? AND time <= ?", $startTime, $endTime); + ->from('table.access_log'); + if ($endTime > 0) { + $subQuery->where("time >= ? AND time <= ?", $startTime, $endTime); + } if(method_exists($subQuery, 'prepare')) $subQuery = $subQuery->prepare($subQuery); $resp['count']['uv'] = intval($this->db->fetchRow( @@ -75,15 +79,16 @@ class Access_Statistic { ->from('(' . $subQuery . ') AS tmp') )['cnt']); # 浏览数 - $resp['count']['pv'] = intval($this->db->fetchRow( - $this->db + $subQuery = $this->db ->select('COUNT(1) AS cnt') - ->from('table.access_log') - ->where("time >= ? AND time <= ?", $startTime, $endTime) - )['cnt']); + ->from('table.access_log'); + if ($endTime > 0) { + $subQuery->where("time >= ? AND time <= ?", $startTime, $endTime); + } + $resp['count']['pv'] = intval($this->db->fetchRow($subQuery)['cnt']); return $resp; } - + /** * 获取文章访问统计 *