mysql 视图 union 慢,包含UNION的MySQL View不能很好地进行优化...换句话说,速度很慢!...

I have a view containing a UNION ALL. For example:

CRATE VIEW myView as

(SELECT col1, col2, col3

FROM tab1)

UNION ALL

(SELECT col1, col2, col3

FROM tab2)

These are large tables containing 10s of millions of rows each. If I write:

SELECT *

FROM myView

LIMIT 1;

instead of being immediate, it basically never returns as do other queries written against this view. If I use the LIMIT in a query against the individual underlying tables, it is immediate. I have indexes on the underlying tables. It seems like MySQL is creating the entire aggregated data set (queries within the view) for the view before applying any filtration criteria. This is insane. Is this the way MySQL optimizes queries against views? By the way, I can't even run an explain plan against the view because it never returns.

解决方案

The behavior you're experiencing is how non-materialized views are handled on every database. MySQL doesn't support materialized views, and it's view support isn't even on par with competitors...

A non-materialized view is just a shorthand/macro/variable for the query it encapsulates - there's no difference between using:

SELECT *

FROM myView

LIMIT 1

...and:

SELECT x.*

FROM (SELECT col1, col2, col3

FROM TAB1

UNION ALL

SELECT col1, col2, col3

FROM TAB2) x

LIMIT 1

Without an ORDER BY, at best you're going to get the first row based on insertion for your query, you might as well be running:

SELECT col1, col2, col3

FROM TAB1

LIMIT 1

...because it's unlikely to pull records from TAB2 due to the order of records returned by a UNIONed statement. Then there's the matter of dealing with 10's of millions of records...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值