Sql 如何减少select查询的执行时间
我有一个问题,如下所示。我怀疑的是它的记录获取时间。有没有比这种方法更好的获取记录的方法Sql 如何减少select查询的执行时间,sql,sql-server,database,sql-server-2008,Sql,Sql Server,Database,Sql Server 2008,我有一个问题,如下所示。我怀疑的是它的记录获取时间。有没有比这种方法更好的获取记录的方法 select product_code,product_name,price,taxPercentage,discount_type,discount_amount,prof it_type,profit_amount,purchase_code, qty from ( select distinct p.product_code,p.product_name,pid.price,t.perce
select product_code,product_name,price,taxPercentage,discount_type,discount_amount,prof it_type,profit_amount,purchase_code, qty
from (
select distinct p.product_code,p.product_name,pid.price,t.percentage as taxPercentage,p.discount_type,p.discount_amount,p.profit_type,p.profit_amount,
pu.purchase_code,pid.quantity+isnull(sum(sri.quantity),0) -isnull(sum(si.quantity),0) -isnull(sum(pri.quantity),0) as qty
from tbl_product p
left join tbl_purchase_item pid on p.product_code=pid.product_code
left join tbl_purchase pu on pu.purchase_code=pid.purchase_code
left join tbl_tax t on t.tax_code=p.tax_code
left join tbl_sale_item si on si.product_code=p.product_code
left join tbl_sale s on s.sale_code=si.sale_code
left join tbl_sale_return sr on sr.sale_code=s.sale_code
left join tbl_sale_return_item sri on sri.sale_return_code=sr.sale_return_code
left join tbl_purchase_return_item pri on pri.purchase_code=pu.purchase_code
group by p.product_code,p.product_name,pid.price,t.percentage,p.discount_type,p.discount_amount,p.profit_type,p.profit_amount,pu.purchase_code,pid.quantity
) as abc
where qty >0
我不知道你的数据库是什么样子。你有太多的连接,我想这是缓慢的根源 首先,确保已为联接中使用的所有列编制索引 如果这没有帮助,试着做一些。这样,您将在数据库中引入一些冗余,但读取时间将得到改善
选择DISTINCT与GROUP BY?您的疑问?提取时间是几点?您是否检查了执行计划/解释输出?您有太多的左连接、一个可以避免的DISTINCT子句和一个包含太多字段的GROUP子句。您真的需要这些表中的所有数据吗?在子查询中,获取一个名为qty的计算列,并在查询外部添加一个
,其中qty=0
。您可以在子查询本身中包含WHERE子句,该子句将删除qty为0的所有行。请使用EXPLAIN
输出更新您的问题。它将通知使用查询的每个部分获取的行数。此外,似乎更适合问这个问题:)请显示查询计划和架构信息。外部的“where”子句很可能可以替换为“having”子句。“Distinct”可能隐藏了一个您不知道的bug。