mysql5
1.索引
-约束
-加速查找
-频繁查找的列:创建索引
2.ORM框架 -sqlAlchemy
-用类和对象数据库操作
回顾:
1.数据库是什么
2.mysql安装
3.用户授权
4.
数据库操作 字符编码 utf8
数据表
-数据类型
-是否可以为空
-自增
-主键
-外键 foreign key
-一对多
-多对多
-一对一
-唯一索引
数据行
增
删
改
查
排序
分组
条件
链表
left join
right join
inner join
临时表
通配符
分页 limit
组合 union
视图(虚拟)
触发器(增删改)
函数 调用select fun1()
存储过程 (产出:结果集加上伪造的返回值)
-游标
-事务
pymysql
-连接
-操作
-创建游标cursor
-增删改 commit()
-查 ->fetchone() , fetchall()
-存储过程调用方式
-callproc("p1",参数)
-select @_p3_0,@_p3_1 如果有返回值,再执行execute, 用他拿
-sql 注入
-关闭游标
-关闭连接
就跟socket一样,有最大连接数,同一时刻只能有多少客户端来连接。
1.索引
单个索引
普通索引:加速查找
主键索引:加速查找+不能为空+不能重复
唯一索引:加速查找+不能重复
联合索引(多列)
-联合主键索引
-联合唯一索引
-联合普通索引
无索引:从前到后依次查找。
有索引:创建额外的文件(某种格式存储)
索引就是个目录,在创建的时候可能耗时。
create index in_name on test(name);
删掉索引文件
drop index in_name on test;
索引格式种类
hash索引: 索引表,把索引值转换为hash值,一一对应。 castel 789544 数据地址 哈希顺序是不固定的。
缺点:如果取范围的话,比如 id<6,则速度比较慢,因为哈希表顺序不一定的。
btree索引:innodb 用的是btree索引
二叉树(有顺序的排列)
建立索引:
a。额外的文件保存特殊的数据格式
b。查询快,插入跟新删除慢
c。命中索引(就是要用索引才会快)
创建表的时候可以添加,后天也可以添加。
主键索引:
全文索引:以后用第三方工具来写。
普通索引:
create index in_name on test(name);
唯一索引:
create unique index in_name on test(name);
联合索引:
create index in_name on test(name,email);
-最左前缀匹配,
select * from test where email="castiel@.com"; 这样写的话,他就不会用索引去找了。
两个名词(不是真的索引)
覆盖索引:
直接从索引文件中,获得数据。
索引合并:
把多个单列索引合并使用。
联合索引效率 > 索引合并效率。
命中索引:
避免使用like
select * from test where name like "%cn"
避免使用函数
select * from test where reverse(name) = "lesiac"
or(前面是索引,后面不是索引)
select * from test where id = "132" or email ="castiel"
select * from test where id = "132" or email ="@gmail.com" and name ="castiel" 这样则会走索引
类型不一致
select * from test where name = 789;
如果是主键,则会走索引
!=
如果是主键,则会走索引
>
如果是主键,或者索引是整数类型,则会走索引。
order by
根据所引排序时,选择的映射如果不是索引,则不走索引
如果是主键,则还是会走索引。
其他注意事项:
尽量使用短索引
create index in_name on test(title(16)) title列的前16字符作为索引。
重复的,变化少的列不建立索引。
使用连接JOIN代替子查询。
上面的只是一般意义上的命中索引
实际上有没有命中索引,还是看时间。
3.时间
mysql可以给我们预估的语句执行时间(一般是正确的,比如limit 语句是All,但是执行速度很快)。
执行计划: type 类型一般执行效率 all < index < range < index_merge < ref_or_null < ref < eq_ref < system < const
explain select * from test where name = "castiel499";
得到的type选项 ref,表示走了索引
type选项是All,表示全数据表查询,一般他就比较慢。
4.DBA工作
慢日志
-执行时间 > 多少
-未命中索引
-日志文件路径。
配置:
-内存
show variables like "%query%"
set global 变量名 = 值
-配置文件 开启mysqld的时候,进行配置
myqld --defaults-file = "D:\my.conf" my-default.int
slow_query_log = ON
修改配置文件之后,需要重启mysql服务
5.********分页************ 单纯的凭借数据库来分页
select * from test limit 1000,10 他是扫描到1000,取10条,但是扫描多了,也慢。
a。不让看
b。索引表中扫
select * from test where id in (select id from test limit 200000,10)
id不连续,所以无法直接使用id范围进行查找
方案:记录当前页的最大或最小ID
1.页面只有上一页,下一页
max_id = ,min_id=
select * from test where id > max_id limit 10;
select * from test where id < min_id order by id desc limit 10;
2. 上一页 195 [196] 197 198 199 下一页
select * from test where id in (
select id from (select id from test where id > max_id limit 30) as N order by N.id desc limit 10);
select * from test where id > 10080004 limit 10;
posted on 2018-08-17 15:10 castiel_lee 阅读(47) 评论(0) 收藏 举报
浙公网安备 33010602011771号