mysql union all 的效率问题

WBOY
Release: 2016-06-23 14:03:38
Original
2300 people have browsed it


我有几个相同结构的表,需要进行联表查询,我使用如下的语句

select sum(cnt) from (select count(*) as cnt from t1 where a>100 union all select ...) as t;
这一句拿总和的挺快。

select * from t1 where a>100 union all select * from t2 where a>100 union all select * from t3 where a>100 order by b desc limit 0,10000;
这一句效率好像很低,等了很久才出来结果。

应该如何优化,谢谢


回复讨论(解决方案)

第二句有 order by b desc limit 0,10000 估计会影响点,去掉后试试。

第二句有 order by b desc limit 0,10000 估计会影响点,去掉后试试。

我知道原因了,因为每个表的数据量太大,查询的时候是先把几个表的所有符合记录都拿出来,然后再LIMIT的,所以慢。
但是如果在每一个表的查询里加LIMIT、ORDER BY,那样拿出来的数据就不准确了,有办法解决吗。

在 union 结构中,只允许出现一个 order (子查询中的除外)
你的这种写法显然是不合理的,或是说是陈旧的(因为你做了人工分表,且分割不合理)
现在的 mysql 提供了分区的功能,只要设置合理与单个小规模表的速度不相上下(虽然也是切割成了多个数据文件)

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!