索引
#### 對數據庫表的一列或者多列的值進行排序的一種結構(Btree方式)
- 優點:可以加快數據檢索速度
- 缺點:佔用物理儲存空間;當對錶中數據更新時,索引需要動態維護,降低數據維護速度
索引示例:
- 開啓運行時間檢測(
show variables like '%pro%;'
)(set profiling = 1;
) - 執行查詢語句(無索引)(
select name from student where name = 'Tom2000000'
) - 查看執行時間(
show profiles;
) - 在字段創建索引(
create index name on student(name)
) - 再執行查詢語句(
select name from student where name = 'Tom2000000'
) - 查看執行時間(
show profiles;
)
普通索引和唯一索引
可設置多個字段
普通索引:字段值無約束,key標誌爲 mul(`desc 表名;`)
唯一索引:字段值不允許重複,但可爲null,key標誌爲uni
那些字段創建索引:經常用來查詢的字段,where條件判斷字段,order by排序的字段
- 創建表時
create table 表名(字段名 數據類型,index(字段名),unique(字段名));
- 已有表中創建
create [unique] index 索引名 on 表名(字段名);
- 查看索引
desc 表名;
show index from 表名\G;
- 刪除索引
drop index 索引名 on 表名
主鍵(pri)和自增長(auto_increment)
- 創建表時
create table 表名() auto_increment=值;
#設置自增長的起始值
- 已有表添加主鍵
alter table 表名 add primary key(id);
- 已有表操作自增長屬性
alter table 表名 modify id int auto_increment;
alter table 表名 auto_increment=起始值;
- 刪除
alter table 表名 modify id int;
#首先刪除自增長alter table 表名 drop primary key;
#再刪除主鍵