作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个如下所示的查询,它工作正常但未优化,因为运行需要 1.5 秒。如何使其达到优化结果?
select h.keyword_id,
( select count(DISTINCT(user_id)) from history where category_id = 6
and h.keyword_id=keyword_id group by keyword_id ) as cat_6,
( select count(DISTINCT(user_id)) from history where category_id = 7
and h.keyword_id = keyword_id group by keyword_id ) as cat_7
from
history h group by h.keyword_id
历史表
his_id keyword_id category_id user_id
1 1 6 12
2 1 6 12
3 1 7 12
4 1 7 12
5 2 6 13
6 2 6 13
7 2 7 13
8 3 6 13
结果:
keyword_id cat_6 cat_7
1 2 2 (unique users)
2 2 1
3 1 0
最佳答案
您可以像这样重写查询:
select h.keyword_id,
count(distinct if(category_id = 6, user_id, null)) as cat_6,
count(distinct if(category_id = 7, user_id, null)) as cat_7
from
history h
group by h.keyword_id
顺便说一句,您基于样本数据想要的结果是错误的。在每个keyword_id 中始终只有一个不同的user_id。
为了进行更多优化,您必须发布 show create table history
的结果和 explain <your_query>;
的输出
关于MySQL基于单表中具有多个GROUP BY的两列进行多重计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45239802/
我是一名优秀的程序员,十分优秀!