一、关于mysql执行顺序的疑惑
- 查表、连表是怎么个执行顺序?
- 语句实际执行时,索引和数据分布怎么影响顺序?验证顺序用explain看最真实的执行顺序。
1、几个常用关键字的执行顺序
form:对表进行读取
on:对所读表进行ON筛选,只要符合的行才会被记录
join:join链接表产生结果(将大数据量的表最后处理能提高性能)
where:对连表的虚表结果条件过滤,记录符合的记录
group by:将表中唯一的值组合成一组
having:对虚表进行having过滤,记录符合的行
select:选择指定的列,插入到虚表
distinct:对虚表的记录进行去重(如果已经进行group by ,那去重就是多余的操作)
order by:将查询出的记录进行排序
limit:取出指定的行记录,将结果返回
二、添加索引
索引---数据库维护以某种方式引用数据满足特定算法的数据结构
2.1 以修改表的方式添加
添加主键索引
alter table tablename add primary key(couname)
添加唯一索引(unique)
alter table tablename add unique(couname)
添加普通索引
alter table tablename add index index_name(couname);
添加全文索引
alter table tablename add fulltext(couname)
添加多列索引
alter table tablename add index index_name(couname1,couname2...)
2.2 在已建表中添加
普通索引
create index index_name on tablename(couname)
唯一索引
create unique index index_name on tablename(couname)
全文索引
create fulltext index index_name on tablename(couname)
多列索引
create index index_name_age on tablename(name,age)
2.3 新建表时添加
普通索引
create table tablename(couname1 int not null primary key,... index index_name(couname2) )
唯一索引
create table tablename(couname1 int not null primary key,... unique index index_name(couname2) )
全文索引
create table tablename(..., fulltext index index_name(couname) )
多列索引
create table tablename(..., key index_name(couname2,couname3))