Way to improve or eliminate a mysql COUNT

自古美人都是妖i 提交于 2019-12-11 20:24:52

问题


Forgive my ignorance on this question, as I don't have much experience in this area. I have a page that uses a mysql COUNT(*) query to return a user's stats. For example, something like:

SELECT COUNT(*) FROM worker WHERE worker_id = '1234';

It uses the index for worker_id and checking out the EXPLAIN seems that the query looks good. However, this performs absolutely brutally, and can take 5+ seconds for a single query on a table with a million+ rows. Additionally, this is quite a common query, and sometimes it will result in a mysql timeout error with multiple queries trying to run this.

What would be a good way to 'solve' this issue? The information changes quite rapidly so I don't think caching it would work. How would I go about fixing this, and what do some large sites do the show stats (for example, Facebook Friends or Twitter Followers)?


回答1:


First, be sure that you have an index on worker(worker_id).

Second, if the column is really a number and not a string, then don't use single quotes:

SELECT COUNT(*)
FROM worker
WHERE worker_id = 1234;

Third, if you just need to know if the worker exists (and don't actually need the count), then run a query like this:

select 1
from worker
where worker_id = 1234
limit 1;

And check to see if any rows are returned.



来源:https://stackoverflow.com/questions/28705668/way-to-improve-or-eliminate-a-mysql-count

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