网站首页 > 知识剖析 正文
SQL优化-数据库自优化
- 一、表结构
- 二、MySQL自优化
- 三、优化
一、表结构
ddd_cargo表:
ddd_location表:
二、MySQL自优化
针对各类数据库,其是有自己的优化引擎,针对SQL语句会尝试优化,但优化的结果,有时并不是系统想要的。
因此在优化进入深水区后,需要了解到数据库进行优化后的SQL语句是什么??我们可以通过下面的方法查看(需要命令行连入数据库mysql -u root -p sq-test):
–explain执行对应SQL语句
explain select * from ddd_location,ddd_cargo where ddd_cargo.destinationLocation_code=ddd_location.code;
–查看
show warnings;
如图:
自优化后:
Bash
select `sq-test`.`ddd_location`.`code` AS `code`,`sq-test`.`ddd_location`.`name` AS `name`,`sq-test`.`ddd_cargo`.`id`
AS `id`,`sq-test`.`ddd_cargo`.`sender_phone` AS `sender_phone`,`sq-test`.`ddd_cargo`.`description` AS `description`,`sq-test`.`ddd_cargo`.`originLocation_code` AS `originLocation_code`,`sq-test`.`ddd_cargo`.`destinationLocation_code` AS `destinationLocation_code`,`sq-test`.`ddd_cargo`.`created_at` AS `created_at`,`sq-test`.`ddd_cargo`.`updated_at` AS `updated_at` from `sq-test`.`ddd_location`
join `sq-test`.`ddd_cargo`
where (`sq-test`.`ddd_cargo`.`destinationLocation_code` = `sq-test`.`ddd_location`.`code`)
可以看到mysql优化器将普通的多表查询的sql优化成了连接查询,提升效率。
再试一个更明显的:
Bash
explain select ddd_cargo.sender_phone from ddd_location,ddd_cargo where ddd_cargo.destinationLocation_code=ddd_location.code;
自优化后:
select `sq-test`.`ddd_cargo`.`sender_phone` AS `sender_phone` from `sq-test`.`ddd_location`
join `sq-test`.`ddd_cargo`
where (`sq-test`.`ddd_cargo`.`destinationLocation_code` = `sq-test`.`ddd_location`.`code`)
三、优化
需求:尝试查询已有货物的运送目的地
explain select * from `sq-test`.ddd_location where code in( select `sq-test`.ddd_cargo.destinationLocation_code from `sq-test`.ddd_cargo);
自优化后SQL:
select `sq-test`.`ddd_location`.`code` AS `code`,`sq-test`.`ddd_location`.`name` AS `name` from `sq-test`.`ddd_location`
semi join (`sq-test`.`ddd_cargo`)
where (`sq-test`.`ddd_location`.`code` = `sq-test`.`ddd_cargo`.`destinationLocation_code`)
可以发现其是先join再where查询的,从SQL优化角度看,先子查询,再in效率会有提升。
改写后的SQL:
select temp.* from
(select distinct(`sq-test`.ddd_cargo.destinationLocation_code) from `sq-test`.ddd_cargo) temp
inner join `sq-test`.ddd_location
on temp.destinationLocation_code=ddd_location.code;
- 上一篇: 44研读分享:在Origin生成的图窗里添加文字
- 下一篇: 如何查找网站源IP地址
猜你喜欢
- 2024-11-24 浏览器跨域问题以及常用解决方案
- 2024-11-24 14个前端小知识,我猜你每天都会遇到
- 2024-11-24 跨域问题的4种解决方案
- 2024-11-24 什么是跨域?跨域解决方法
- 2024-11-24 构建rancher自定义ui的前端镜像
- 2024-11-24 你应该知道的前端小知识,初学者,确定不点进来看看吗?
- 2024-11-24 15个前端小知识
- 2024-11-24 记一场纯JS赛——DiceCTF2021 Web题解
- 2024-11-24 如何基于 Elasticsearch 实现排序沉底或前置
- 2024-11-24 如何查找网站源IP地址
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)