[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
<>1. 如何做sql优化
explain分析sql的执行计划
<>1.1 insert语句的优化
在大批量插入数据时,对于InnoDB的表,有以下几种提高导入效率方式
* 主键顺序插入(主键有序的话,插入效率高)
* 关闭唯一性校验
* 手动提交事务
对一张表插入多行数据时,可以使用多个值表的insert语句;这种方式可以缩减客户端与数据库之间的连接、关闭等消耗
insert into tb_test values(1,'Tom'); insert into tb_test values(2,'Cat');
insert into tb_test values(3,'Jerry');
优化后
insert into tb_test values(1,'Tom'),(2,'Cat'),(3,'Jerry');
<>1.2 order by语句优化
filesort排序:先返回数据再排序
index排序:直接返回有序数据(需要select后面跟索引字段)
尽量添加索引,让MySQL使用index排序
而且order by的字段要么都是升序,要么都是降序
否则会造成filesort 排序
<>1.3 group by语句优化
group by后最好跟上有索引的字段
如果没有索引,那么加上order by null
可以避免效率低的filesort
因为group by也会进行排序操作
<>1.4 or查询优化
因为使用or查询时,or两边字段必须都有索引,才能利用索引,容易造成索引失效。
所以我们用union关键字代替or,union可以连接两个select语句,代替or的作用。
<>1.5 优化嵌套查询
用两张表连接查询代替嵌套查询
因为嵌套查询需要在内存中创建临时表,步骤更加繁琐
<>1.6 优化分页查询limit
* 思路一:分页之前得排序,可以选择在索引上完成分页操作,最后根据主键关联回原表查询的其他内容(先把对应页的主键表查出来,再根据主键查出整表)
* 思路二:可以把limit查询转换成某个位置的查询:select * from 表名 where id > 1000000 limit 10;
该方法适用于主键自增的表,且主键不能断层
例如:日志信息表,只有插入没有修改删除。