分享好友 教程首页 教程搜索 频道列表

记mysql的union all的简单优化

2022-03-17 18:5415130
+关注28
核心提示:需用php测试

网站后台最近需要把两张表数据进行统一分页查询,一张表150多万,一张表50多万

首先就想到了union all ,但感觉会很慢, 果不其然, 第一页就花了十几秒, 开始的SQL是这样的:

原方案:

-- 总数
select count(*) from
 (
select id,order_no,state,create_time from order1
 union all 
select id,order_no,state,create_time from order2
 ) ua where state=1 
 
-- 分页
select * from
 (
select id,order_no,state,create_time from order1
 union all 
select id,order_no,state,create_time from order2
 ) ua where state=1 
order by create_time desc 
limit 0,10;


细思极恐之后, 决定还是要优化一下, 效果不错, 最重要的两个优化如下:

1,  如果有筛选条件, 务必先各自筛选, 分而治之然后再进行union

优化后的方案:

-- 总数
select count(*) from
 (
select id from order1 where state=1 
 union all 
select id from order2 where state=1 
 ) ua ;
 
-- 分页
select * from
 (
select id,order_no,state,create_time from order1 where state=1
 union all 
select id,order_no,state,create_time from order2 where state=1
 ) ua 
order by create_time desc 
limit 0,10;


2, 如果没有任何筛选条件, 务必充分利用“覆盖索引”- Covering Index

覆盖索引,简单理解就是 select 字段(身上有索引) from table , 这种情况不会去遍历表, 使用explain解释覆盖索引语句时,会显示type为index , extra为Using index

当无筛选条件进行分页时, 首先利用覆盖索引快速查出一页的id, 然后再用in去查询出该页的行数据

-- 覆盖索引, 假如id是主键, create_time身上有索引
select * from
 (
select id,create_time from order1 
 union all 
select id,create_time from order2 
 ) ua order by create_time desc
limit 0,10;
 
-- 根据上面查询出的id,再去in查询指定的行数据
select * from
 (
select id,order_no,state,create_time from order1 where id in (...)
 union all 
select id,order_no,state,create_time from order2 where id in (...)
 ) ua


本文标签: #数据库 #优化 #连表 #查询
整理员:小黑
免责声明:凡注明来源本网的所有作品,均为本网合法拥有版权或有权使用的作品,欢迎转载,注明出处。非本网作品均来自互联网,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。
生成海报
您可能在找更多

在大数据下,DESTOON换域名好的方案(官方推荐)

    如本站数据库有5G的数据了,换域名按照之前的小数据方案:备份-替换-还原 这样太耗时也容易502页面错误,官方推荐法,看图注意事项:1、先在宝塔里做好站点的SQL备份2、不选择表3、查找: 需要填写绝对网址,如:htt

小黑 destoon数据库相关2023-08-03

解决Lnmp一键包环境忘记MySQL管理员密码问题

    这个问题是前几天老蒋遇到一个网友在使用军哥LNMP一键包环境的时候,告知他好久没有登录phpMyadmin,居然忘记密码,这个问题也是经常遇到的。有些网友的所有的服务器、网站密码都会用一些通用的或者随机设置的且在开

网络转载 LNMP2023-02-03

lnmp快速备份恢复配置和数据库

    用代码自行测试

网络转载 LNMP2023-02-03

php循环输出数据库内容的代码

    请用代码测试

网络转载 PHP2022-08-28

Sql性能优化之UNION、UNION ALL

    需在php中测试

小黑 MYSQL2022-03-17

下一篇
我来说两句
抢沙发