Maison > Article > développement back-end > mysql中sum的优化和索引问题
//表结构CREATE TABLE IF NOT EXISTS `radacct` ( `RadAcctId` bigint(21) NOT NULL AUTO_INCREMENT, `UserName` varchar(64) NOT NULL DEFAULT '', `AcctSessionTime` int(12) DEFAULT NULL, `AcctInputOctets` bigint(12) DEFAULT NULL, `AcctOutputOctets` bigint(12) DEFAULT NULL, ... ...... PRIMARY KEY (`RadAcctId`), KEY `UserName` (`UserName`), KEY `AcctSessionTime` (`AcctSessionTime`), KEY `AcctInputOctets` (`AcctInputOctets`), KEY `AcctOutputOctets` (`AcctOutputOctets`)) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=456017; $sql = 'SELECT UserName, count(*) AS numOfSession, sum(AcctSessionTime) AS Time, sum(AcctInputOctets) AS Upload, sum(AcctOutputOctets) AS Download, sum(AcctInputOctets+AcctOutputOctets) AS Bandwidth FROM radacct GROUP BY UserName'; mysql> explain SELECT UserName, count(*) AS numOfSession, sum( AcctSessionTime ) AS Time, sum( AcctInputOctets ) AS Upload, sum( AcctOutputOctets ) AS Download, sum( AcctInputOctets + AcctOutputOctets ) AS Bandwidth FROM radacct GROUP BY UserName; +----+-------------+---------+------+---------------+------+---------+------+--------+---------------------------------+| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |+----+-------------+---------+------+---------------+------+---------+------+--------+---------------------------------+| 1 | SIMPLE | radacct | ALL | NULL | NULL | NULL | NULL | 456010 | Using temporary; Using filesort |+----+-------------+---------+------+---------------+------+---------+------+--------+---------------------------------+
首先,如果使用的计算,索引就已经失效了,所以你加不加索引没效果。
我的思路是这样的,如果表变得的不平凡,可以考虑缓存一份数据的办法来代替你每次的查询。
首先,如果使用的计算,索引就已经失效了,所以你加不加索引没效果。
我的思路是这样的,如果表变得的不平凡,可以考虑缓存一份数据的办法来代替你每次的查询。
好了 骚年 再没人来分都全给你了
加上分页什么的就更慢了我的思路是这样的,如果表变得的不平凡,可以考虑缓存一份数据的办法来代替你每次的查询。