gpt4 book ai didi

mysql - 从mysql订单表中获取上升速度但是太慢了

转载 作者:行者123 更新时间:2023-11-29 02:05:48 25 4
gpt4 key购买 nike

我在 mysql 中有一个产品订单表。是这样的:

create table `order`
(productcode int,
quantity tinyint,
order_date timestamp,
blablabla)

然后,为了获得增长率,我写了这个查询:

SELECT thismonth.productcode,
(thismonth.ordercount-lastmonth.ordercount)/lastmonth.ordercount as riserate
FROM ( (SELECT productcode,
sum(quantity) as ordercount
FROM `order`
where date_format(order_date,'%m') = 12
group by productcode) as thismonth,
(SELECT productcode,
sum(quantity) as ordercount
FROM `order`
where date_format(order_date,'%m') = 11
group by productcode) as lastmonth)
WHERE thismonth.productcode = lastmonth.productcode
ORDER BY riserate;

但它在我的电脑上运行了大约 30 秒(200000 条记录,200MB(包括其他字段))。有什么办法可以提高查询速度吗?我已经为产品代码字段创建了索引。

我认为性能低下的原因是“GROUP BY”,有什么不同的方法吗?

我试过你的答案,但它们似乎都不起作用,我想知道索引是否有问题(不是我创建的),所以我删除所有索引并重新创建它们,一切正常-- 只需要3-4秒。我的查询和你的查询之间的区别不是很明显。但真的谢谢你们,我学到了很多:)

最佳答案

尝试在 (ORDER_DATE, PRODUCTCODE) 上添加索引并更改查询以消除对 DATE_FORMAT 函数的使用,如:

SELECT thismonth.productcode,
(thismonth.ordercount-lastmonth.ordercount)/lastmonth.ordercount as riserate
FROM ( (SELECT productcode,
sum(quantity) as ordercount
FROM `order`
WHERE ORDER_DATE BETWEEN '01-12-2010' AND '31-12-2010'
GROUP BY PRODUCTCODE) as thismonth,
(SELECT productcode,
sum(quantity) as ordercount
FROM `order`
WHERE ORDER_DATE BETWEEN '01-11-2010' AND '30-11-2010'
group by productcode) as lastmonth)
WHERE thismonth.productcode = lastmonth.productcode
ORDER BY riserate;

分享和享受。

关于mysql - 从mysql订单表中获取上升速度但是太慢了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6237166/

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