Million-level mysql database uses count, group, order query is very slow, how to optimize

the database currently has 1 million data (it has been running for about half a month)

the following sentence takes 6 seconds to run (1 million results for where alone), and both user_id and time are indexed

   


found the problem and learned a new knowledge.

SELECT user_id,count(*) as count from prize_numbers where user_id > 0 and time > 1545972485 GROUP BY user_id ORDER BY count desc

as mentioned, the query takes 6 seconds, and user_id,time has an index set up.
after many attempts, I found that the query speed of the following two sentences is very fast, within 1 second.

SELECT user_id,count(*) as count from prize_numbers where time > 1545972485 GROUP BY user_id ORDER BY count desc
SELECT user_id,count(*) as count from prize_numbers where user_id > 0 GROUP BY user_id ORDER BY count desc

searched a lot of information and saw something called aggregate index. I tried it, and the speed was fast at once. The statement is as follows:

alter table  add index   (1,2) 

for example, my:

alter table prize_numbers add index union_user_id_time (user_id, time) 

what fields should be added to the aggregate index? I roughly understand that the conditional fields after the where statement are added to an aggregate index.


SELECT user_id,count(id) as count from prize_numbers where user_id > 0 and time > 1545972485 GROUP BY user_id ORDER BY count desc
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e38596-594f8.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e38596-594f8.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?