mysql 优化 视图_如何优化MySQL视图
我有一些查询使用视图,这些运行速度比我预期的要快得多,因为所有相关的表都被编入索引(并且不管怎么说都不大).
我希望我能解释一下:
我的主要查询看起来像这样(非常简化)
select [stuff] from orders as ord
left join calc_order_status as ors on (ors.order_id = ord.id)
calc_order_status是一个视图,因此定义:
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 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
我的猜测是,“derived2”指的是视图.单个项目(itm)似乎工作正常,按order _ id索引.问题似乎是第4行,这表明系统不使用订单表(ord)的密钥.但是在MAIN查询中,订单ID已经定义:
左连接calc_order_status为ors on(ors.order _ id = ord.id)
和ord.id(在主查询和视图内)引用主键.
我读过的地方比MySQL simpliy没有很好地优化视图,即使在可用的情况下也可能不会在某些条件下使用密钥.这似乎是其中一种情况.
我将不胜感激任何建议.有没有办法迫使MySQL意识到“它比你想象的更简单,只需使用主键就可以了”?或者观点是错误的方式来解决这个问题?
我有一些查询使用视图,这些运行速度比我预期的要快得多,因为所有相关的表都被编入索引(并且不管怎么说都不大). 我希望我能解释一下: 我的主要查询看起来像这样(非常简化) select [stuff] from orders as ord left join calc_order_status as ors on (ors.order_id = ord.id) calc_order_status是一个视图,因此定义: 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 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 我的猜测是,“derived2”指的是视图.单个项目(itm)似乎工作正常,按order _ id索引.问题似乎是第4行,这表明系统不使用订单表(ord)的密钥.但是在MAIN查询中,订单ID已经定义: 左连接calc_order_status为ors on(ors.order _ id = ord.id) 和ord.id(在主查询和视图内)引用主键. 我读过的地方比MySQL simpliy没有很好地优化视图,即使在可用的情况下也可能不会在某些条件下使用密钥.这似乎是其中一种情况. 我将不胜感激任何建议.有没有办法迫使MySQL意识到“它比你想象的更简单,只需使用主键就可以了”?或者观点是错误的方式来解决这个问题?