523 字
3 分钟
索引
索引
索引的概念
索引的存储结构
创建索引
-- 为员工表创建一个first_name的索引 create index employee_index1 on employee(first_name) -- 为员工表创建一个岗位和工资的索引 create index employee_index2 on employee(job_id,salary) -- 为员工表创建一个联系方式的唯一索引 create unique index employee_index3 on employee(phone_number) select * from employee where first_name = 'tom' alter table employee add address varchar(255) -- 创建员工表 地址 的全文索引 create fulltext index employee_index_addr on employee(address) with parser ngram select address from employee where match(address) against('大庆') select address from employee where match(address) against(' +黑龙江 -大庆' in boolean mode)MyISAM 引擎 和 InnoDB引擎 索引存储的区别
SQL优化
分为三个步骤:
-
慢查询 : 建立一个慢日志,找出哪些SQL语句执行的速度慢
在数据库的配置文件my.ini中找到:
slow_query_log_file=“WW-slow.log”
long_query_time=10
-
查询分析 : explain 或 desc + SQL语句 执行 ,就会看到SQL语句执行的分析结果
eq_ref : 在做多表连接时,尽量设置外键约束,因为外键是另一个表的主键,是主键索引而非普通索引 ref : 在做多表连接时,连接字段都是两个表的普通索引 ; 辅助索引等值查找
-
尽量使用主键或唯一约束查询
-
多表连接时,尽量为连接字段设置外检约束,如果不是外键约束,也要设置普通索引
-
能用 = 的条件就不用 < 或 >
-
在order by group by 尽量使用索引,查找的字段尽量是索引字段
-
-
SQL语句优化 1. 复合索引 字段是有顺序的,查询条件要遵循 最左原则 ,查询条件是没有顺序的 2. 不要在列上进行运算 3. 避免查询条件中对字段进行函数操作 4. in尽量改成exists 5. null值的处理:列中尽量不存储null值,采用设置非空属性,设置默认值方式 6. 尽量不要使用* 7. 如果某列要设置为索引,这列数据的前几个字符重复率非常低,考虑可以使用短索引
MySQL基础
Related articles
部分信息可能已经过时