通过分组内部查询和计数优化查询。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通过分组内部查询和计数优化查询。相关的知识,希望对你有一定的参考价值。
我想获取相对的标签。
我在标签和帖子表之间有很多关系。
例如,对于 "爱 "这个标签,我试图获取他们发布的所有标签。Love
标签。
这是我的查询(标签67是 "爱 "的意思)。
SELECT hashtag_id, count(hashtag_id) as count
from post_hashtag
where
# where posts has hashtag '67'
post_id in ( SELECT post_id FROM post_hashtag WHERE hashtag_id = 67 )
# remove hashtag 67 from result
and hashtag_id != 67
# group them and sort by count, so the must repeated hashtag is the best relative hashtag
GROUP by hashtag_id
ORDER by count desc
limit 4
我试着优化我的查询,但我不能更多的优化(目前需要2-12秒的时间,根据帖子的数量)。
有什么办法可以优化吗?
解释查询
+----+-------------+-----------------+------------+--------+---------------+---------------------------------------------------+---------+-------------------------------------------+---------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-----------------+------------+--------+---------------+---------------------------------------------------+---------+-------------------------------------------+---------+----------+-------------+
| 1 | SIMPLE | post_hashtag | NULL | index | NULL | fk_np_account_post_has_np_hashtag_np_hashtag1_idx | 4 | NULL | 4623584 | 100.00 | Using index |
| 1 | SIMPLE | hashtag | NULL | eq_ref | PRIMARY | PRIMARY | 4 | graphicj_novin.np_post_hashtag.hashtag_id | 1 | 100.00 | NULL |
+----+-------------+-----------------+------------+--------+---------------+---------------------------------------------------+---------+-------------------------------------------+---------+----------+-------------+
post_hashtag
有这些领域
post_id,hashtag_id
两个字段都是外键
答案
mysql经常优化 WHERE IN (SELECT ...)
差。用一个 JOIN
而不是。
SELECT p1.hashtag_id, count(*) as count
from post_hashtag AS p1
JOIN post_hashtag AS p2 ON p1.post_id = p2.post_id
WHERE p1.hashtag_id != 67
AND p2.hashtag_id = 67
GROUP by p1.hashtag_id
ORDER by count desc
limit 4
以上是关于通过分组内部查询和计数优化查询。的主要内容,如果未能解决你的问题,请参考以下文章