以下查询需要花费太多时间(目前为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_price表的连接(和总和),因为两个表中都有很多行(项目) :16974,item_price:23981)因为每个项目都有一个或多个item_prices,总计订单金额。
如何更快地进行此查询?
答案 0 :(得分:1)
您可以尝试使用相关子查询而不是public class UnorderedEnumerableComparer<T> : IEqualityComparer<IEnumerable<T>>
{
public bool Equals(IEnumerable<T> x, IEnumerable<T> y)
{
return x.OrderBy(i => i).SequenceEqual(y.OrderBy(i => i));
}
// Just the count of the array,
// it violates the rule of hash code but should be fine here
public int GetHashCode(IEnumerable<T> obj)
{
return obj.Count();
}
}
:
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