我有一些使用 View 的查询,这些查询的运行速度比我预期的要慢得多,因为所有相关表都已建立索引(而且没有那么大)。
我希望我能解释一下:
我的主要查询如下所示(大大简化)
select [stuff] from orders as ord
left join calc_order_status as ors on (ors.order_id = ord.id)
calc_order_status
是一个 View ,定义如下:
create view calc_order_status as
select ord.id AS order_id,
(sum(itm.items * itm.item_price) + ord.delivery_cost) AS total_total
from orders ord
left join order_items itm on itm.order_id = ord.id
group by ord.id
订单 (ord) 包含订单,order_items
包含与每个订单关联的各个商品及其价格。
所有表都已正确索引,但是运行速度很慢,当我执行 EXPLAIN 时,我得到了
# id select_type table type possible_keys key key_len ref rows Extra
1 1 PRIMARY ord ALL customer_id NULL NULL NULL 1002 Using temporary; Using filesort
2 1 PRIMARY <derived2> ALL NULL NULL NULL NULL 1002
3 1 PRIMARY cus eq_ref PRIMARY PRIMARY 4 db135147_2.ord.customer_id 1 Using where
4 2 DERIVED ord ALL NULL NULL NULL NULL 1002 Using temporary; Using filesort
5 2 DERIVED itm ref order_id order_id 4 db135147_2.ord.id 2
我的猜测是,“衍生2”指的是 View 。各个项目 (itm) 似乎工作正常,按订单 _ id 索引。问题似乎出在第 4 行,这表明系统没有使用订单表 (ord) 的键。但在 MAIN 查询中,订单 id 已经定义: 将 calc_order_status 左连接为 ors on (ors.order _ id = ord.id) 和ord.id(在主查询和 View 中)引用主键。
我在某处读过,MySQL 简单地不能很好地优化 View ,并且在某些条件下即使可用也可能不会使用键。这似乎就是其中之一。
如有任何建议,我将不胜感激。有没有办法强制MySQL认识到“这一切比你想象的要简单,只要使用主键就可以了”?或者观点根本就是错误的解决方法吗?
最佳答案
如果可以删除这些连接,请将其删除。用子查询替换它们会大大加快速度。
您也可以尝试运行类似的东西,看看它是否有任何速度差异。
select [stuff] from orders as ord
left join (
create view calc_order_status as
select ord.id AS order_id,
(sum(itm.items * itm.item_price) + ord.delivery_cost) AS total_total
from orders ord
left join order_items itm on itm.order_id = ord.id
group by ord.id
) as ors on (ors.order_id = ord.id)
关于mysql - 如何优化 MySQL View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1021319/