mysql中sum的优化和索引问题
程序员文章站
2024-01-08 18:04:52
...
//表结构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 |+----+-------------+---------+------+---------------+------+---------+------+--------+---------------------------------+
数据量大概45w左右 在sum的字段上加上索引也无法提高查询效率
加上分页什么的就更慢了
怎么优化比较好啊 先拜谢了
回复讨论(解决方案)
首先,如果使用的计算,索引就已经失效了,所以你加不加索引没效果。
我的思路是这样的,如果表变得的不平凡,可以考虑缓存一份数据的办法来代替你每次的查询。
首先,如果使用的计算,索引就已经失效了,所以你加不加索引没效果。
我的思路是这样的,如果表变得的不平凡,可以考虑缓存一份数据的办法来代替你每次的查询。
好了 骚年 再没人来分都全给你了
加上分页什么的就更慢了我的思路是这样的,如果表变得的不平凡,可以考虑缓存一份数据的办法来代替你每次的查询。