两个MySQL视图非常慢

时间:2018-06-11 09:12:54

标签: mysql

我一直试图让这个问题解决一段时间,而且我没有到达任何地方。我的数据库中有两个视图比其他任何视图慢得多。其中一个需要1.5秒生成,另一个需要3s。我知道如果我扫描大量行,这些值会没问题,但我每个视图只使用少于5,000行。

服务器运行在配备2x Intel Hexa-Core Xeon E5-2420 CPU的32GB RAM专用计算机上。

在这个screenshot中,您可以看到我使用Percona Tools for MySQL生成的当前my.cnf配置。

需要3秒生成的视图,代码可以在下面看到

let attributeString = NSMutableAttributedString(string: text)
attributeString.removeAttribute(NSAttributedStringKey.strikethroughStyle, range: NSMakeRange(0, attributeString.length))
attributeString.removeAttribute(NSAttributedStringKey.strikethroughColor, range: NSMakeRange(0, attributeString.length))

可以看到Explain查询here

我在生成视图时使用的所有列上都有索引。

我遇到问题的第二种观点如下:

CREATE ALGORITHM=UNDEFINED DEFINER=`easycoun_st`@`localhost` SQL SECURITY DEFINER VIEW `view_stocktake_summary`  AS  select `stocktake_locations`.`stocktake_id` AS `stocktake_id`,(select `stocktake_master`.`store_id` from `stocktake_master` where `stocktake_master`.`id` = `stocktake_locations`.`stocktake_id`) AS `store_id`,(select `stocktake_master`.`stock_date` from `stocktake_master` where `stocktake_master`.`id` = `stocktake_locations`.`stocktake_id`) AS `stock_date`,(select sum(`stocktake_details`.`quantity` * `stocktake_details`.`unit_of_measure` + `stocktake_details`.`quantity_units`) from `stocktake_details` where `stocktake_details`.`stocktake_id` = `stocktake_locations`.`stocktake_id`) AS `total_quantity`,(select sum(`stocktake_details`.`quantity` * `stocktake_details`.`full_cost` + `stocktake_details`.`quantity_units` * `stocktake_details`.`unit_cost`) from `stocktake_details` where `stocktake_details`.`stocktake_id` = `stocktake_locations`.`stocktake_id`) AS `total_cost` from `stocktake_locations` group by `stocktake_locations`.`stocktake_id` ;

再次解释查询here

与以前相同,所有列都有索引。为什么两个视图的生成速度如此之慢?我的配置有什么问题,或者它实际上是子查询的数量?

提前谢谢。

1 个答案:

答案 0 :(得分:0)

您可以尝试使用正确的JOIN,而不是将连接作为选择列。

select 
  l.stocktake_id AS 'stocktake_id',
  m.store_id as 'store_id',
  m.stock_date as 'stock_date',
  sum(d.quantity *d.unit_of_measure + d.quantity_units) as 'total_quantity',
  sum(d.quantity * d.full_cost + d.quantity_units * d.unit_cost) as 'total_cost'
from stocktake_locations l
  join stocktake_master m on m.id = l.stocktake_id
  join from stocktake_details d on d.stocktake_id = l.stocktake_id
group by l.stocktake_id, m.store_id, m.stock_date;

请注意,视图不包含任何限制性WHERE子句,因此MySQL将使用的唯一索引是表之间的连接。

相关问题