简体   繁体   中英

Mysql Very Slow Performance Using Order by Clause

I have a one table with millions of entry.Below is table structure.

CREATE TABLE `useractivity` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
 `userid` bigint(20) NOT NULL,
 `likes` bigint(20) DEFAULT NULL,
 `views` bigint(20) DEFAULT NULL,
 `shares` bigint(20) DEFAULT NULL,
 `totalcount` bigint(20) DEFAULT NULL,
 `status` bigint(20) DEFAULT NULL,
 `createdat` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `userid` (`userid`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

And Below is query in which i am getting slow performance.

SELECT userid, 
 (sum(likes)+SUM(views)+SUM(shares)+SUM(totalcount)+SUM(`status`)) as total
from useractivity
GROUP BY userid
ORDER BY total DESC
limit 0, 20;

When i am executing above query without ORDER BY then it gives me fast result set But when using ORDER BY then this query became slow,though i used limit for pagination.

What can I do to speed up this query?

You can't speed up the query as it is, MySQL needs to visit every single row and calculate the sum before sorting and finally returning the first rows. That is bound to take time. You can probably cheat though.

The most obvious approach would be to create a summary table with userid and total. Update it when the base table changes or recompute it regularly, whatever makes sense. In that table you can index total, which makes the query trivial.

Another option may be to find the top users. Most sites have users that are more active than the others. Keep the 1000 top users in a separate table, then use the same select but only for the top users (ie join with that table). Only the useractivity rows for the top users need to be visited, which should be fast. If 1000 users are not enough perhaps 10000 works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM