gpt4 book ai didi

MySQL 优化 avg、sum 查询有 left join 嵌套 select

转载 作者:行者123 更新时间:2023-11-29 11:58:55 33 4
gpt4 key购买 nike

是否要针对 MySQL 5.1 优化此查询?

我有“Calls”表,有字段“Caller”(从号码),“Callee”(到号码)和“Duration”,这个查询在SQLite中工作正常,但在MySQL中非常慢,数据量为140亿记录一下。

我在“调用者”字段上有索引。

select A.Caller, ifnull(aCallOut, 0) as CallOut, round((ifnull(aDuration, 0) / 60), 2) as Duration, round((ifnull(aAverage, 0) / 60), 2) as Average, Times, 0, 0, 0, 0
from
(
select Caller, sum(duration) as aDuration, count(*) Times -- sum of duration of each caller
from Calls
group by Caller
) As A

left join
(
select Caller, avg(duration) as aAverage -- i want avg duration of numbers that calling more than 0 seconds
from Calls
where Duration > 0
group by Caller
) as C
on A.Caller = C.Caller

left join
(
select Caller, count(*) as aCallOut -- i need to count how many numbers that caller called, ignoring the duplicating calls
from
(
select Caller, count(*) aCount
from Calls
group by Caller, Callee
) as D
group by Caller
) as B
on A.Caller = B.Caller

最佳答案

您可以通过条件聚合来完成所有这些:

select Caller, sum(duration) as aDuration, count(*) as Times,
avg(case when duration > 0 then duration end) as aAverage,
count(distinct Callee) as aCallOut
from Calls
group by Caller;

小提示:如果 CalleeNULL,则 aCallOut 可能会减少 1。

关于MySQL 优化 avg、sum 查询有 left join 嵌套 select,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32704502/

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