3399 mysql_MySQL索引
索引:類似于書的目錄,飯店的菜單,字典的目錄
功能:加快數據檢索速度,提高效率
缺點:
1)創建和維護索引都需要消耗時間,消耗時間的長短取決于表中數據量的多少
2)會占用磁盤空間
3)更新數據庫中的數據時,索引也會更新
什么時候都可以創建索引嗎?
不是。對于數據頻繁更新的表不適合創建索引。(更新包括insert、update、delete)
索引的分類
單列索引、多列索引、唯一性索引
一、創建索引
1、在創建表時直接創建索引
create table 表名 (字段名 字段類型,...,index [索引名](索引字段列表));
mysql> create table ind1 (id int,name char(10),index (id));
mysql> show create table ind1\G
*************************** 1. row***************************
Table: ind1
Create Table: CREATE TABLE `ind1` (
`id` int(11) DEFAULT NULL,
`name` char(10) DEFAULT NULL,
KEY `id` (`id`)//索引相關的行 ? KEY 索引名 (索引字段)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
創建索引時不指定名字,那么默認會創建與字段名同名的索引。
2、使用create index命令創建索引
語法:create index 索引名(必有) on 表名(字段名);
mysql> create index ind1_name on ind1(name);
mysql> show create table ind1\G
*************************** 1. row ***************************
Table: ind1
Create Table: CREATE TABLE `ind1` (
`id` int(11) DEFAULT NULL,
`name` char(10) DEFAULT NULL,
KEY `id` (`id`),
KEY `ind1_name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
3、對于已經存在的表,添加索引
語法:alter table 表名 add index [索引名](字段名);
mysql> alter table score add index s_sno(sno);
唯一性索引: unique index ?[索引名](索引字段)
mysql> alter table score add unique index s_sname(sname);
二、查看索引
mysql> show create table score\G
或者
mysql> show index from score\G
三、刪除索引
1、drop index 索引名 on 表名;
mysql> drop index s_sno on score;
2、alter table 表名 drop index 索引名;
mysql> alter table score drop index score_sno;
測試:
1、創建表
mysql> create table shop (id int,name varchar(20),price float(10,2),street varchar(20),city varchar(20));
2、寫腳本生成插入語句
[~]# vim insert.sh
#!/bin/bash
i=1
while [ $i -le 1000000 ]
do
echo "insert into shop values ($i,‘name$i‘,$i.00,‘street$i‘,‘city$i‘);" >> /tmp/a.sql
echo $i
let i++
done
3、執行腳本生成sql文件
[~]# sh insert.sh ? //執行完成再做第4步
4、向數據庫中插入數據
mysql> use up1;
Database changed
mysql> source /tmp/a.sql ? //比較慢
mysql> select count(*) from up1.shop; ?//查看已經向表中插入了多少數據
+----------+
| count(*) |
+----------+
| ? ? 3280 |
+----------+
1 row in set (0.45 sec)
5、開啟可以查看每個select語句執行時間的功能
mysql> show variables like ‘%profi%‘;
+------------------------+-------+
| Variable_name ? ? ? ? ?| Value |
+------------------------+-------+
| have_profiling ? ? ? ? | YES ? |
| profiling ? ? ? ? ? ? ?| OFF ? |
| profiling_history_size | 15 ? ?|
+------------------------+-------+
3 rows in set (0.16 sec)
mysql> set profiling=1; ? ?//打開性能分析功能
6、創建一張帶索引的表
mysql> create table shop1 (id int,name varchar(20),price float(10,2),street varchar(20),city varchar(20),index(id));
7、復制表shop到shop1
mysql> insert into shop1 select * from shop;
8、對兩個表分別執行sql語句
先查看shop表:
mysql> select * from shop;
select id from shop;
select * from shop where id=1;
select id,name from shop where id=1;
select * from shop where id=650000;
select id,name from shop where id=650000;
select id from shop where price=10000.00;
show profiles;
總結
以上是生活随笔為你收集整理的3399 mysql_MySQL索引的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python小游戏编程100例_经典编程
- 下一篇: mysql 5.7 centos 7_C