沉浸式阅读
Beta
原创

记mysql的union all的简单优化

     订阅 PHP     2022-03-17     www.mbkfw.com    小黑    1487    0    0    0    2022-03-17
学习要点:需用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


本文标题: 记mysql的union all的简单优化

本文链接: https://www.mbkfw.com/course/1037.html (转载时请注明来源链接)

本文说明: 有问题或投稿请发送至: 邮箱/kf@dtmuban.com    QQ/290948585

特别鸣谢: 如果您觉得本文对您有帮助,请给我们一个小小的赞,收藏本文更利于反复学习哦!

 
本文标签: #数据库 #优化 #连表 #查询
destoon程序前端开发标签生成器

下班PC阅读不方便?

手机也可以随时学习开发

微信关注公众号“商企云服”
"模板开发网前端开发教学"
每日干货技术分享
 
0

圈友点评

文明上网理性发言,请遵守网络评论服务协议

小编推荐



色彩
×

《客户实名在线注册登记》售后一直都在!

关注

微信
关注

微信扫一扫
不同的环境体验

幸运大转盘,好礼等您拿

模板开发网公众号

模板开发网微信小程序

代授权

程序
授权

黑小二

联系
客服

很高兴为您服务
尊敬的用户,欢迎您咨询,我们为新用户准备了优惠好礼。咨询客服

联系客服:

在线QQ: 290948585

客服电话: 18605917465

E_mail邮箱: kf@dtmuban.com

微信公众号: 商企云服

微信小程序: 模板开发

QQ客服 微信客服DT授权代办 在线交谈 智能小云

工作时间:

周一至周五: 09:00 - 18:00

APP下载

安卓
APK

模板开发网安卓版APP

反馈

我要
反馈