索引本质上是数据库引擎用来快速查找数据的数据结构
但是会增加数据库的大小,因为他们必须永久存储在表的旁边
每次我们增加、更新或删除记录时,mysql必须更新对应的索引,这会影响我们正常操作的性能(也就是用空间换取时间)
我们不应该基于表来创建索引,而是基于查询创建索引
索引内部通常被存储为二叉树
--此时是全表扫描
--可以在select前面加上explain来显示的更详细
select customer_id from customers where state='CA';
--创建索引
--create index 索引名字 on 需要建立在哪个表的名字(哪一列)
create index idx_state on customers(state);
--这时候不再是全表扫描
--每当我们在表中添加主键时,mysql会自动创建一个索引
show index in customers;
如果需要建立的索引的列时字符串类型(char、varchar、blog、text)时,我们的索引就可能会占用大量的空间,且无法达到更好的性能,索引越小越好
--last_name括号是你想指定的前n个字符,注意列一定要是字符串类型
create index idx_lastname on customers(last_name(20))
看其他博客吧