我想计算每个地点的商品净额。这涉及2个表:股票和位置。表格股票衍生出4种观点: view_cr , view_dr , view_union_crdr , view_net_stocks 。
表格股票的指数:id,code,type,dr_coloumn,id-code-type。 表位置上的索引:id_locations,type,id_locations-type。
观点是:
view_cr:
SELECT cr_coloumn AS TOTAL FROM stocks
view_dr:
SELECT (0-dr_coloumn) AS TOTAL FROM stocks WHERE dr_coloumn > 0
view_union_crdr:
SELECT * FROM view_cr UNION SELECT * FROM view_dr
view_net_stocks:
SELECT SUM(TOTAL), type, code, id
FROM view_union_crdr VUCRDR
JOIN locations LOC
ON (LOC.id = VUCRDR.id
AND LOC.type = VUCRDR.type )
GROUP BY VUCRDR.code, VUCRDR.id, VUCRDR.type`
每当我执行SELECT * FROM view_net_stocks时,它需要超过20秒。我觉得它仍然会变慢......股票的记录数量只有65400条记录。
如何改进查询?
感谢
(来自评论)
CREATE
ALGORITHM=UNDEFINED DEFINER=root@%`
SQL SECURITY DEFINER
VIEW tsj_stock_opname3 AS
select sum(vij.total) AS mytotal, vij.tsj_ml_id AS tsj_ml_id,
vij.tsj_mi_name AS tsj_mi_name, vij.tsj_mi_code AS tsj_mi_code,
vij.tsj_ml_type AS tsj_ml_type, b.ml_name AS ml_name
from (union_cr_dr2 vij
join v_locations2 b on(((vij.tsj_ml_id = b.ml_id)
and (vij.tsj_ml_type = b.ml_type)))
)
group by vij.tsj_mi_code, vij.tsj_ml_id, vij.`tsj_ml_type``
答案 0 :(得分:0)
手册dev.mysql.com/doc/refman/5.7/en/view-restrictions.html声明视图处理未优化:无法在视图上创建索引。索引可用于使用合并算法处理的视图。但是,使用temptable算法处理的视图无法利用其基础表上的索引(尽管可以在生成临时表期间使用索引)。 和 对于UNDEFINED,MySQL选择使用哪种算法。如果可能的话,它更喜欢MERGE而不是TEMPTABLE,因为MERGE通常更有效,并且如果使用临时表,则视图无法更新。 在创建视图时尝试显式设置算法。