一、 前言导读
TiDB作为NewSQL , 其在对MySQL(SQL92协议)的兼容上做了很多 , MySQL作为当下使用较广的事务型数据库 , 在IT界尤其是互联网间使用广泛 , 那么对于开发人员来说 , 1)两个数据库产品在SQL开发及调优的过程中 , 都有哪些差异?在系统迁移前需要提前做哪些准备? 2)TiDB的执行计划如何查看 , 如何SQL调优? 本文做了一个简要归纳 , 欢迎查阅交流 。
二、 建表SQL语法差异&优化建议分类
MySQL写法
TiDB写法
注意事项
建表
alter table A add column phone bigint(20),add column address varchar(100);
alter table A add column phone bigint(20); alter table A add column address varchar(100);
1.一个DDL脚本仅支持一个字段修改 2.新建表时 , 尽量提前规划好相应字段
建表
create table A(`id` bigint(20) NOT NULL AUTO_INCREMEN)
create table A(`id` bigint(20) NOT NULL AUTO_INCREMEN)
TiDB自增主键全局唯一 , 但不严格递增(仅各Server内部连续) 需要严格连续自增主键时 , 业务系统自己生成写入
建表
create table A as select * from B
不支持
建表
create temporary table A
不支持
不支持临时表
SQL DML提交前 , 建议结合explain和explain analyze命令和业务场景 , 确认执行计划
三、 查询SQL语法差异&优化建议分类
MySQL写法
TiDB写法
注意事项
查询 (结果条数统计)
select * from A select count(*) from A
select name,age,address from A select count(age) from A
1.避免全量字段查询 , 节省网络带宽 2.当开启TiFlash统计行数据时 , TiDB会使用列模式提升查询性能
查询 (闭区间查询)
select name,age from A where age>10
select name,age from A where age>10 and id<99
TiDB针对限定数据范围的闭区间查询 , 能减少全表扫描概率
查询 (时间排序)
select name,age from A order by id(主键)
select name,age from A order by create_time(时间索引)
分布式数据库主键不再连续 , 需要时间顺序排序时 , 可新增时间字段
查询 (结果字段分堆)
select name,age from A group by name
select name,age from A group by name,age
需要分堆的所有字段 , 在SQL中必须显示标识
查询 (结果字段排序)
select name,age from A order by name
select name,age from A order by name,age
需要排序的所有字段 , 在SQL中必须显示标识
查询 (索引优化)
select name,age from A where name=‘张三’ and age>110 and cityName!='北京'
尽可能的将使用频率高的 , 经常被点查使用的列排在前面 , 将经常进行范围查询的列排在后面
查询 (显示优化规则) DBA不建议
select name,age from A where name='张三'
select name,age from A where name='张三' use index(name_age)
显示通知TiDB优化器 , 使用name_age索引
查询 (覆盖索引)
select name,age from A where name='张三' order by age
ORDER BY , GROUP BY , DISTINCT 的字段需要添加在索引的后面 , 形成覆盖索引
查询 (显示优化规则) DBA不建议
select name,age from A where name='张三'
select /*+ read_from_storage(tiflash[A]) */ name,age from A where name='张三'
显示通知TiDB优化器 , 使用TiFlash提升性能
MySQL常见SQL优化规则(如not in , like ‘abc%’ , 减少查询返回列 , 避免在索引列使用函数) , 对于TiDB同样适用
四、 SQL执行计划差异&优化建议分类
MySQL写法
TiDB写法
注意事项
执行计划
explain select count(*) from A
explain select count(*) from A explain analyze select count(*) from A
1.TiDB提供explain和explain analyze两种查询计划分析 , 前者不会执行 , 后者会实际执行 2.explain参考:
https://docs.pingcap.com/zh/tidb/stable/explain-walkthrough 3.explain analyze参考:https://docs.pingcap.com/zh/tidb/stable/sql-statement-explain-analyze/
查询 (结果分析优化)
operator中包含stats:pseudo
SQL对应表统计信息已失真 , 执行analyze tableName修复即可(注:关注数据期间卡表修复对业务的影响)
查询 (类型优化)
select name,age from A where zip=0 (其中zip为bit类型)
推荐阅读
- 带你读 MySQL 源码:Select *
- 指针与内存对齐到底是什么鬼?
- 潮汕美食:探索舌尖上的美味与文化
- 生姜薏米水功效与作用
- 生姜紫苏水功效与作用
- 白酒泡樱桃功效与作用
- 于和伟|于和伟乱睡门后露面,与风波女主眼神躲闪刻意避嫌王丽坤再受累
- |解读电视剧《爱情而已》探寻当代人情感、职场与家庭之路
- 面膜泥的功效与作用,面膜泥的正确使用方法 面膜泥多久后洗掉?
- 附桂骨痛颗粒的功效与作用