gpt4 book ai didi

MySQL 查询速度极慢

转载 作者:行者123 更新时间:2023-11-29 11:38:53 27 4
gpt4 key购买 nike

以下查询花费了太多时间(目前为 0.8169 秒)来显示 20 个条目,但我找不到原因...

SELECT
`Order`.ID,
Order_Type.Description as OrderTypeDescription,
`Order`.OrderType as OrderType,
DATE_FORMAT(`Order`.InsertDate, '%d.%m.%Y') as OrderInsertDate,
round(sum(Item_Price.Amount),2) as OrderAmount,
c1.ID as buyerCustomerId,
c2.ID as sellerCustomerId,
c1.CompanyName as BuyerCompany,
c2.CompanyName as SellerCompany,
c1.ID as BuyerCustomer,
c2.ID as SellerCustomer
FROM `Order`
INNER JOIN Order_Type ON Order_Type.ID=`Order`.OrderType
INNER JOIN Customer as c1 ON c1.ID=`Order`.BuyerCustomer
INNER JOIN Customer as c2 ON c2.ID=`Order`.SellerCustomer
INNER JOIN Item ON Item.`Order`=`Order`.ID
INNER JOIN Item_Price ON Item_Price.Item=Item.ID
GROUP BY `Order`.ID,OrderType,OrderTypeDescription,buyerCustomerId,sellerCustomerId,BuyerCustomer,SellerCustomer
ORDER BY `Order`.ID DESC
LIMIT 20

EXPLAIN 显示以下输出:http://pastebin.com/5f9QYizq

我不太擅长优化查询,但我认为性能不佳的原因可能是 item 和 item_price 表上的联接(和总和),因为两个表中都有很多行(item :16974,item_price:23981),因为每件商品都有一个或多个item_prices,总计为订单金额。

有什么想法可以让这个查询更快吗?

最佳答案

您可以尝试使用相关子查询而不是group by:

SELECT o.ID, ot.Description as OrderTypeDescription, ot.OrderType as OrderType,
DATE_FORMAT(o.InsertDate, '%d.%m.%Y') as OrderInsertDate,
(SELECT round(sum(ip.Amount), 2)
FROM Item i INNER JOIN
Item_Price ip
ON ip.Item = i.ID
WHERE i.`Order` = o.ID
) as OrderAmount,
c1.ID as buyerCustomerId,
c2.ID as sellerCustomerId,
c1.CompanyName as BuyerCompany,
c2.CompanyName as SellerCompany,
c1.ID as BuyerCustomer,
c2.ID as SellerCustomer
FROM `Order` o INNER JOIN
Order_Type ot
ON ot.ID = o.OrderType INNER JOIN
Customer c1
ON c1.ID = o.BuyerCustomer INNER JOIN
Customer c2
ON c2.ID = `Order`.SellerCustomer
ORDER BY o.ID DESC
LIMIT 20;

这应该可以节省GROUP BY开销。

您甚至可以将 LIMIT 移至子查询,假设联接未过滤任何行:

SELECT o.ID, ot.Description as OrderTypeDescription, ot.OrderType as OrderType,
DATE_FORMAT(o.InsertDate, '%d.%m.%Y') as OrderInsertDate,
(SELECT round(sum(ip.Amount), 2)
FROM Item i INNER JOIN
Item_Price ip
ON ip.Item = i.ID
WHERE i.`Order` = o.ID
) as OrderAmount,
c1.ID as buyerCustomerId,
c2.ID as sellerCustomerId,
c1.CompanyName as BuyerCompany,
c2.CompanyName as SellerCompany,
c1.ID as BuyerCustomer,
c2.ID as SellerCustomer
FROM (SELECT o.*
FROM `Order` o
ORDER BY o.id DESC
) o INNER JOIN
Order_Type ot
ON ot.ID = o.OrderType INNER JOIN
Customer c1
ON c1.ID = o.BuyerCustomer INNER JOIN
Customer c2
ON c2.ID = `Order`.SellerCustomer
ORDER BY o.ID DESC
LIMIT 20;

关于MySQL 查询速度极慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36144246/

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