复习
1.数据库是什么
2.SQL 安装
3.用户授权
4.数据库的各种操作
1.库
2.表
-数据类型
-外键
一对多
多对多
一对一
-自增
3.行
排序:order by
分组
条件
连表
临时表
通配符
分页
组合
4.视图
5.触发器
6.函数
7.存储过程
游标
事务
动态执行SQL
8.pymysql
1.存储过程的调用方式
2.conmmit
3.SQL注入,SQL中注释为--
学习内容
1.索引
1.作用
1.约束
2.加速查找
2.类型
1.普通索引:加速查找
2.主键索引:加速查找+不为空+不能重复
3.唯一索引:加速查找+不能重复
4.联合作引:(组合索引)
-联合唯一索引
-联合主键索引
-联合普通索引
3.加速查找
无索引:从前到后一次查找
索引:
根据索引列,创建文件相应提高查找速度
索引种类:
hash索引
单值快
范围查找慢
btree索引
二叉树
4.建立索引
1.额外的文件保存特殊的数据结构
2.查询快,插入 更新 删除慢
3.命中索引
select * from xx where oo=‘aa’ 命中
select * from xx where oo like ‘aa_’ 没命中
4.SQL语句
普通索引
-create index xx on 表名(列)
-drop index xx on 表名(列)
唯一索引
-create unique index xx on 表名(列)
-drop unique index xx on 表名(列)
组合索引
1.最左前缀匹配
create index ix_name_email on userinfo3 (name,email)
命中
select * from userinfo3 where name='alex'
select * from userinfo3 where name='alex' and email'sss'
不能命中
select * from userinfo3 where email'sss'
2.组合索引效率>索引合并
5.名词
覆盖索引
-在索引文件中直接获取数据
-select name from userinfo3 where name='alex' (name索引)
索引合并
-把多个单列索引合并使用
select * from userinfo3 where name='alex' and id=11 (name,id都创建了索引)
6.频繁查找的列创建索引
1.创建索引
2.命中索引
列举部分常见不能命中索引的情况
表 id, email为索引,其中id为主键, name无索引
1.like
select * from xx where email like 'c%'
2.使用函数
select * from xx where reverse(email) = 'cc'
3.or
select * from xx where id = 1 or name = 'cc'
or中含有未建立索引的列,失效
4.类型不一致
select * from xx where email = 11;
如果是主键,应该还是能命中
5.!=
select * from xx where email = 'c'
如果是主键,还是能走索引
6.>
select * from xx where email > 'c%'
如果是主键,或者索引类型为整数,还能走索引
7.order by
select name from xx order by email desc
如果根据索引排序,选择映射的不是索引,则不走索引
根据主键排序,还是能走索引
8.组合索引最左前缀
7.优化
1.注意事项
1.避免使用select *
2.count(1)或count(列)替代count(*)
3.尽量使用char替代varchar(牺牲存储空间,换取性能)
4.索引散列值(重复少)不适合建索引,例如:性别
5.表的字段顺序固定长度的字段优先
6.组合索引代替多个单列索引(经常使用多个条件查询时)
7.尽量使用短索引
8.连表时注意条件类型一致
2.执行计划
mysql预估计执行操作
根据type估计
all<index<range<index_merge<ref_or_null<ref<eq_ref<system/const
详细参见
https://www.cnblogs.com/wupeiqi/articles/5716963.html
http://www.cnblogs.com/xiaoboluo768/p/5400990.html
http://dev.mysql.com/doc/refman/5.7/en/explain-output.html#jointype_system
3.慢日志
1.条件
1.执行时间纪录
2.未命中索引
3.日志文件路径
2.配置
1.在内存中直接待配置项
-show variables like '%query%'
-set global 变量名 = 值
2.配置文件
1.文件my-default.ini 为配置文件,更改内部数据,重启mysql
2.启动mysqld时,备注配置文件位置
mysqld --defaults-file='E...\my-default.ini'
3.修改内容与内存中修改几乎相同
8.分页
1.实际网站会禁止用户访问部分数据
2.解决办法
1.select * from xx where id in (select id from xx limit 200000,10) 通过命中索引,但是效果不是很明显
2.纪录当前页得最大最小ID(实际也是这么做的)
下一页
select * from xx where id>200000 limit 10;
上一页
select * from xx where id<200000 order by id desc limit 10; (通过主键order by 不会很慢)
跳转某页:上一页 1 2 ... [98] 99 100 ... 下一页
select * from xx where id in (
select id from
(select id from xx where id > max_id limit 20) as T
order by T.id desc limit 10
)
3.通过between and 无法实现,因为id不一定连续