//索引相关的行 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、写脚本生成插入语句
[root@s200 ~]# 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文件
[root@s200 ~]# 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;
mysql> select * from shop1;
mysql> select id from shop1;
mysql> select * from shop1 where id=1;
mysql> select id,name from shop1 where id=1;
mysql> select * from shop1 where id=650000;
mysql> select id,name from shop1 where id=650000;
mysql> select id from shop1 where price=10000.00;
MySQL索引
标签:mysql