Speeding up count(distinct) of one column based on condition on other column in MySQL

生来就可爱ヽ(ⅴ<●) 提交于 2020-12-13 03:34:21

问题


I have a MySQL table of 10 million rows and 3 columns, in following format:

+---------------------------------------------------------------------------------------+
|     id                                     time                               num     |
+---------------------------------------------------------------------------------------+
| ca65e871-d758-437e-b76f-175234760e7b  2020-11-14 23:08:05.553770          11112222222 |
| ...                                                                                   |
+---------------------------------------------------------------------------------------+

For running the first query below, I indexed the table on (num, time) and it works very fast (<5 milliseconds on 10 million rows table):

SELECT COUNT(*) 
FROM TABLE_NAME 
WHERE time >= '2020-11-14 23:08:05.553752' AND num = 11112222222

However, I also need to execute count(distinct) clause on one column given the condition on other column, like this:

SELECT COUNT(DISTINCT time) 
FROM TABLE_NAME 
WHERE time >= '2020-11-14 23:08:05.553752' AND num = 11112222222

This runs for around 20 milliseconds which is also very fast, but I was wondering is there a way to make it even faster (maybe similar to the execution time of the first query - less than 5 milliseconds) ?

来源:https://stackoverflow.com/questions/65005378/speeding-up-countdistinct-of-one-column-based-on-condition-on-other-column-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!