gpt4 book ai didi

MySQL基于单表中具有多个GROUP BY的两列进行多重计数

转载 作者:行者123 更新时间:2023-11-29 18:36:37 25 4
gpt4 key购买 nike

我有一个如下所示的查询,它工作正常但未优化,因为运行需要 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。

  • 您可以在 sqlfiddle here 中看到正在执行的查询

为了进行更多优化,您必须发布 show create table history 的结果和 explain <your_query>; 的输出

关于MySQL基于单表中具有多个GROUP BY的两列进行多重计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45239802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com