mysql count group by order by optimization

ぐ巨炮叔叔 提交于 2019-11-30 18:00:36

问题


I have a table to store tag name for posts

table: tagname
tags                    |  pid
festival                | 10034
New York Fashion Week   | 10034
festival                | 10035
car                     | 10036
...

The table now has already 590,000 records. Now I want to get the first 10 most popular tags from this table.

SELECT tags, COUNT(*) as Num FROM tagname
GROUP BY tags
ORDER BY Num DESC

This will cost 23.88 seconds. return 358 kinds of tags

tags       |  Num
festival   |  7201
art        |  6988
gift       |  6755
...

How to optimization this query, even in my.cnf? I tried to add index for tags, it seems with no effect.

EDIT: EXPLAIN SELECT tags, COUNT(tags) as Num FROMtagnameGROUP BY tags order by Num DESC

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   SIMPLE      tagname ALL     NULL    NULL     NULL    NULL   597649  Using temporary; Using filesort

回答1:


Add an index to your tags column:

ALTER TABLE `tagname` 
ADD INDEX `tags_index` (`tags` ASC) ;

EDIT:

Try creating a second index

CREATE INDEX tags_pid_index ON tagname (tags, pid);

Then modify your query to:

SELECT tags, COUNT(pid) as Num 
FROM tagname
GROUP BY tags
ORDER BY Num DESC



回答2:


Have you tried like this:

    SELECT tags, COUNT(*) as Num FROM tagname
    GROUP BY tags HAVING COUNT(*) > 1
    ORDER BY Num DESC LIMIT 10

The trick can be: If you know the minimum popularity number, you can change the number in COUNT(*) > x

Thanks



来源:https://stackoverflow.com/questions/10329024/mysql-count-group-by-order-by-optimization

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