一、MySQL的基本使用
1.1数据库简介
1.1.1 RDBMS
Relational Database Management System
通过表来表示关系型
1.1.2 SQL
Structured Query Language
SQL是结构化查询语言,是一种用来操作RDBMS的数据库语言,当前关系型数据库都支持使用SQL语言进行操作,也就是说可以通过 SQL 操作 oracle,sql server,mysql,sqlite 等等所有的关系型的数据库
1.1.3 MySQL
MySQL 简介
特点
1.2数据完整性
数据类型
'ab '
约束
数值类型(常用)
类型 | 字节大小 | 有符号范围(Signed) | 无符号范围(Unsigned) |
---|---|---|---|
TINYINT | 1 | -128 ~ 127 | 0 ~ 255 |
SMALLINT | 2 | -32768 ~ 32767 | 0 ~ 65535 |
MEDIUMINT | 3 | -8388608 ~ 8388607 | 0 ~ 16777215 |
INT/INTEGER | 4 | -2147483648 ~2147483647 | 0 ~ 4294967295 |
BIGINT | 8 | -9223372036854775808 ~ 9223372036854775807 | 0 ~ 18446744073709551615 |
字符串
类型 | 字节大小 | 示例 |
---|---|---|
CHAR | 0-255 | 类型:char(3) 输入 'ab', 实际存储为'ab ', 输入'abcd' 实际存储为 'abc' |
VARCHAR | 0-255 | 类型:varchar(3) 输 'ab',实际存储为'ab', 输入'abcd',实际存储为'abc' |
TEXT | 0-65535 | 大文本 |
日期时间类型
类型 | 字节大小 | 示例 |
---|---|---|
DATE | 4 | '2020-01-01' |
TIME | 3 | '12:29:59' |
DATETIME | 8 | '2020-01-01 12:29:59' |
YEAR | 1 | '2017' |
TIMESTAMP | 4 | '1970-01-01 00:00:01' UTC ~ '2038-01-01 00:00:01' UTC |
1.3命令行脚本
命令行连接
mysql -uroot -p 回车后输入密码,当前设置的密码为mysql
quit 和 exit 或 ctrl+d
查看版本:select version(); 显示当前时间:select now();
1.3.1 数据库操作
show databases;
use 数据库名;
select database();
create database 数据库名 charset=utf8;
drop database 数据库名;
1.3.2 数据表操作
show tables;
desc 表名;
CREATE TABLE table_name( column1 datatype contrai,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY(one or more columns) );
View Code
例:创建班级表
create table classes( id int unsigned auto_increment primary key not null, name varchar(10) );
View Code
例:创建学生表
create table students( id int unsigned primary key auto_increment not null,
name varchar(20) default '',
age tinyint unsigned default 0,
height decimal(5,2),
gender enum('男','女','保密'),
cls_id int unsigned default 0 )
View Code
alter table 表名 add 列名 类型; 例: alter table students add birthday datetime;
alter table 表名 change 原名 新名 类型及约束; 例: alter table students change birthday birth datetime not null;
alter table 表名 modify 列名 类型及约束; 例: alter table students modify birth date not null;
alter table 表名 drop 列名; 例: alter table students drop birthday;
drop table 表名; 例: drop table students;
show create table 表名; 例: show create table classes;
1.3.3 数据增删改查(curd)
增删改查(curd)
curd的解释: 代表创建(Create)、更新(Update)、读取(Retrieve)和删除(Delete)
查询基本使用
select * from 表名; 例:select * from classes;
select 列1,列2,... from 表名; 例:select id,name from classes;
增加
格式:INSERT [INTO] tb_name [(col_name,...)] {VALUES | VALUE} ({expr | DEFAULT},...),(...),...
insert into 表名 values(...) 例:insert into students values(0,’郭靖‘,1,'蒙古','2019-1-2');
insert into 表名(列1,...) values(值1,...) 例:insert into students(name,hometown,birthday) values('黄蓉','桃花岛','2019-3-2');
insert into 表名 values(...),(...)...;
例:
insert into classes values(0,'python1'),(0,'python2');
insert into 表名(列1,...) values(值1,...),(值1,...)...;
例:
insert into students(name) values('杨康'),('杨过'),('小龙女');
View Code
修改
格式: UPDATE tbname SET col1={expr1|DEFAULT} [,col2={expr2|default}]...[where 条件判断]
update 表名 set 列1=值1,列2=值2... where 条件 例:update students set gender=0,hometown='北京' where id=5;
删除
DELETE FROM tbname [where 条件判断]
delete from 表名 where 条件 例:delete from students where id=5;
update students set isdelete=1 where id=1;
1.3.4 数据备份与恢复
备份
mysqldump –uroot –p 数据库名 > python.sql; # 按提示输入mysql的密码
恢复
mysql -uroot –p 新数据库名 < python.sql # 根据提示输入mysql密码
二、 MySQL-查询
2.1 MySQL查询
查询
创建数据库、数据表
-- 创建数据库
create database python_test_1 charset=utf8;
-- 使用数据库
use python_test_1;
create table students(
id int unsigned primary key auto_increment not null,
name varchar(20) default '',
age tinyint unsigned default 0,
height decimal(5,2),
gender enum('男','女','保密') default '保密',
cls_id int unsigned default 0,
is_delete bit default 0
);
-- students表
create table classes (
id int unsigned auto_increment primary key not null,
name varchar(30) not null
);
-- classes表
准备数据
insert into students values
(0,'小明',18,180.00,2,1,0),
(0,'小月月',18,180.00,2,2,1),
(0,'彭于晏',29,185.00,1,1,0),
(0,'刘德华',59,175.00,1,2,1),
(0,'黄蓉',38,160.00,2,1,0),
(0,'凤姐',28,150.00,4,2,1),
(0,'王祖贤',18,172.00,2,1,1),
(0,'周杰伦',36,NULL,1,1,0),
(0,'程坤',27,181.00,1,2,0),
(0,'刘亦菲',25,166.00,2,2,0),
(0,'金星',33,162.00,3,3,1),
(0,'静香',12,180.00,2,4,0),
(0,'郭靖',12,170.00,1,4,0),
(0,'周杰',34,176.00,2,5,0);
-- 向students表中插入数据
insert into classes values (0, "python_01"), (0, "python_02");
-- 向classes表中插入数据
select * from 表名; 例: select * from students;
select 列1,列2,... from 表名; 例: select name from students;
select id as 序号, name as 名字, gender as 性别 from students;
消除重复行
select distinct 列1,... from 表名; 例: select distinct gender from students;
2.2 条件
使用where子句对表中的数据筛选,结果为true的行会出现在结果集中
select * from 表名 where 条件; 例:select * from students where id=1;
比较运算符
例1:查询编号大于3的学生
select * from students where id > 3;
例2:查询编号不大于4的学生
select * from students where id <= 4;
例3:查询姓名不是“黄蓉”的学生
select * from students where name != '黄蓉';
例4:查询没被删除的学生
select * from students where is_delete=0;
例子
逻辑运算符
例5:查询编号大于3的女同学
select * from students where id > 3 and gender=0;
例6:查询编号小于4或没被删除的学生
select * from students where id < 4 or is_delete=0;
例子
模糊查询
例7:查询姓黄的学生
select * from students where name like '黄%';
例8:查询姓黄并且“名”是一个字的学生
select * from students where name like '黄_';
例9:查询姓黄或叫靖的学生
select * from students where name like '黄%' or name like '%靖';
例子
范围查询
例10:查询编号是1或3或8的学生
select * from students where id in(1,3,8);
between ... and ...表示在一个连续的范围内
例11:查询编号为3至8的学生
select * from students where id between 3 and 8;
例12:查询编号是3至8的男生
select * from students where (id between 3 and 8) and gender=1;
例子
空判断
例13:查询没有填写身高的学生
select * from students where height is null;
判非空is not null
例14:查询填写了身高的学生
select * from students where height is not null;
例15:查询填写了身高的男生
select * from students where height is not null and gender=1;
例子
优先级
2.3 排序
为了方便查看数据,可以对数据进行排序
select * from 表名 order by 列1 asc|desc [,列2 asc|desc,...]
例1:查询未删除男生信息,按学号降序
select * from students where gender=1 and is_delete=0 order by id desc;
例2:查询未删除学生信息,按名称升序
select * from students where is_delete=0 order by name;
例3:显示所有的学生信息,先按照年龄从大-->小排序,当年龄相同时 按照身高从高-->矮排序
select * from students order by age desc,height desc;
例子
2.4聚合函数
为了快速得到统计数据,经常会用到如下5个聚合函数
例1:查询学生总数
select count(*) from students;
例子
例2:查询女生的编号最大值
select max(id) from students where gender=2;
例子
例3:查询未删除的学生最小编号
select min(id) from students where is_delete=0;
例子
例4:查询男生的总年龄
select sum(age) from students where gender=1;
-- 平均年龄
select sum(age)/count(*) from students where gender=1;
例子
例5:查询未删除女生的编号平均值
select avg(id) from students where is_delete=0 and gender=2;
例子
2.5分组
group by
select * from students;
+----+-----------+------+--------+--------+--------+-----------+
| id | name | age | height | gender | cls_id | is_delete |
+----+-----------+------+--------+--------+--------+-----------+
| 1 | 小明 | 18 | 180.00 | 女 | 1 | |
| 2 | 小月月 | 18 | 180.00 | 女 | 2 | |
| 3 | 彭于晏 | 29 | 185.00 | 男 | 1 | |
| 4 | 刘德华 | 59 | 175.00 | 男 | 2 | |
| 5 | 黄蓉 | 38 | 160.00 | 女 | 1 | |
| 6 | 凤姐 | 28 | 150.00 | 保密 | 2 | |
| 7 | 王祖贤 | 18 | 172.00 | 女 | 1 | |
| 8 | 周杰伦 | 36 | NULL | 男 | 1 | |
| 9 | 程坤 | 27 | 181.00 | 男 | 2 | |
| 10 | 刘亦菲 | 25 | 166.00 | 女 | 2 | |
| 11 | 金星 | 33 | 162.00 | 中性 | 3 | |
| 12 | 静香 | 12 | 180.00 | 女 | 4 | |
| 13 | 周杰 | 34 | 176.00 | 女 | 5 | |
| 14 | 郭靖 | 12 | 170.00 | 男 | 4 | |
+----+-----------+------+--------+--------+--------+-----------+
select gender from students group by gender;
+--------+
| gender |
+--------+
| 男 |
| 女 |
| 中性 |
| 保密 |
+--------+
根据gender字段来分组,gender字段的全部值有4个'男','女','中性','保密',所以分为了4组 当group by单独使用时,只显示出每组的第一条记录, 所以group by单独使用时的实际意义不大
例子
group by + group_concat()
select gender from students group by gender;
+--------+
| gender |
+--------+
| 男 |
| 女 |
| 中性 |
| 保密 |
+--------+
select gender,group_concat(name) from students group by gender;
+--------+-----------------------------------------------------------+
| gender | group_concat(name) |
+--------+-----------------------------------------------------------+
| 男 | 彭于晏,刘德华,周杰伦,程坤,郭靖 |
| 女 | 小明,小月月,黄蓉,王祖贤,刘亦菲,静香,周杰 |
| 中性 | 金星 |
| 保密 | 凤姐 |
+--------+-----------------------------------------------------------+
select gender,group_concat(id) from students group by gender;
+--------+------------------+
| gender | group_concat(id) |
+--------+------------------+
| 男 | 3,4,8,9,14 |
| 女 | 1,2,5,7,10,12,13 |
| 中性 | 11 |
| 保密 | 6 |
+--------+------------------+
例子
group by + 集合函数
值的集合
做一些操作
select gender,group_concat(age) from students group by gender;
+--------+----------------------+
| gender | group_concat(age) |
+--------+----------------------+
| 男 | 29,59,36,27,12 |
| 女 | 18,18,38,18,25,12,34 |
| 中性 | 33 |
| 保密 | 28 |
+--------+----------------------+
分别统计性别为男/女的人年龄平均值
select gender,avg(age) from students group by gender;
+--------+----------+
| gender | avg(age) |
+--------+----------+
| 男 | 32.6000 |
| 女 | 23.2857 |
| 中性 | 33.0000 |
| 保密 | 28.0000 |
+--------+----------+
分别统计性别为男/女的人的个数
select gender,count(*) from students group by gender;
+--------+----------+
| gender | count(*) |
+--------+----------+
| 男 | 5 |
| 女 | 7 |
| 中性 | 1 |
| 保密 | 1 |
+--------+----------+
例子
group by + having
select gender,count(*) from students group by gender having count(*)>2;
+--------+----------+
| gender | count(*) |
+--------+----------+
| 男 | 5 |
| 女 | 7 |
+--------+----------+
例子
group by + with rollup
select gender,count(*) from students group by gender with rollup;
+--------+----------+
| gender | count(*) |
+--------+----------+
| 男 | 5 |
| 女 | 7 |
| 中性 | 1 |
| 保密 | 1 |
| NULL | 14 |
+--------+----------+
select gender,group_concat(age) from students group by gender with rollup;
+--------+-------------------------------------------+
| gender | group_concat(age) |
+--------+-------------------------------------------+
| 男 | 29,59,36,27,12 |
| 女 | 18,18,38,18,25,12,34 |
| 中性 | 33 |
| 保密 | 28 |
| NULL | 29,59,36,27,12,18,18,38,18,25,12,34,33,28 |
+--------+-------------------------------------------+
例子
2.6分页
语法
select * from 表名 limit start,count
说明
例1:查询前3行男生信息
select * from students where gender=1 limit 0,3;
例子
示例:分页
select * from students where is_delete=0 limit (n-1)*m,m
例子
2.7连接查询
当查询结果的列来源于多张表时,需要将多张表连接成一个大的数据集,再选择合适的列返回
mysql支持三种类型的连接查询,分别为:
语法
select * from 表1 inner或left或right join 表2 on 表1.列 = 表2.列
例1:使用内连接查询班级表与学生表
select * from students inner join classes on students.cls_id = classes.id;
例2:使用左连接查询班级表与学生表
此处使用了as为表起别名,目的是编写简单
select * from students as s left join classes as c on s.cls_id = c.id;
例3:使用右连接查询班级表与学生表
select * from students as s right join classes as c on s.cls_id = c.id;
例4:查询学生姓名及班级名称
select s.name,c.name from students as s inner join classes as c on s.cls_id = c.id;
例子
2.8自关联
问题:
能不能将两个表合成一张表呢?
思考:
观察两张表发现,citys表比provinces表多一个列proid,其它列的类型都是一样的
意义:
存储的都是地区信息,而且每种信息的数据量有限,没必要增加一个新表,或者将来还要存储区、乡镇信息,都增加新表的开销太大
答案:
定义表areas,结构如下
说明:
创建areas表的语句如下:
create table areas(
aid int primary key,
atitle varchar(20),
pid int
);
View Code
source areas.sql;
View Code
select count(*) from areas where pid is null;
View Code
例1:查询省的名称为“山西省”的所有城市
select city.* from areas as city
inner join areas as province on city.pid=province.aid
where province.atitle='山西省';
例2:查询市的名称为“广州市”的所有区县
select dis.* from areas as dis
inner join areas as city on city.aid=dis.pid
where city.atitle='广州市';
例子
2.9子查询
子查询
在一个 select 语句中,嵌入了另外一个 select 语句, 那么被嵌入的 select 语句称之为子查询语句
主查询
主要查询的对象,第一条 select 语句
主查询和子查询的关系
子查询分类
标量子查询
查询班级学生的平均身高
select * from students where age > (select avg(age) from students);
View Code
select name from classes where id in (select cls_id from students);
View Code
行级子查询
select * from students where (height,age) = (select max(height),max(age) from students);
View Code
子查询中特定关键字使用
2.10 总结
查询的完整格式
SELECT select_expr [,select_expr,...] [
FROM tb_name
[WHERE 条件判断]
[GROUP BY {col_name | postion} [ASC | DESC], ...]
[HAVING WHERE 条件判断]
[ORDER BY {col_name|expr|postion} [ASC | DESC], ...]
[ LIMIT {[offset,]rowcount | row_count OFFSET offset}]
]
View Code
select distinct *
from 表名
where ....
group by ... having ...
order by ...
limit start,count
View Code
三、MySQL与Python交互
3.1Python操作MySQL步骤
引入模块
from pymysql import *
Connection 对象
conn=connect(参数列表)
对象的方法
Cursor对象
cs1=conn.cursor()
对象的方法
对象的属性
3.2增删改查
增删改
from pymysql import *
def main():
# 创建Connection连接
conn = connect(host='localhost',port=3306,database='jing_dong',user='root',password='mysql',charset='utf8')
# 获得Cursor对象
cs1 = conn.cursor()
# 执行insert语句,并返回受影响的行数:添加一条数据
# 增加
count = cs1.execute('insert into goods_cates(name) values("硬盘")')
#打印受影响的行数
print(count)
count = cs1.execute('insert into goods_cates(name) values("光盘")')
print(count)
# # 更新
# count = cs1.execute('update goods_cates set name="机械硬盘" where name="硬盘"')
# # 删除
# count = cs1.execute('delete from goods_cates where id=6')
# 提交之前的操作,如果之前已经之执行过多次的execute,那么就都进行提交
conn.commit()
# 关闭Cursor对象
cs1.close()
# 关闭Connection对象
conn.close()
if __name__ == '__main__':
main()
View Code
查询一行数据
from pymysql import *
def main():
# 创建Connection连接
conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
# 获得Cursor对象
cs1 = conn.cursor()
# 执行select语句,并返回受影响的行数:查询一条数据
count = cs1.execute('select id,name from goods where id>=4')
# 打印受影响的行数
print("查询到%d条数据:" % count)
for i in range(count):
# 获取查询的结果
result = cs1.fetchone()
# 打印查询的结果
print(result)
# 获取查询的结果
# 关闭Cursor对象
cs1.close()
conn.close()
if __name__ == '__main__':
main()
View Code
查询多行数据
from pymysql import *
def main():
# 创建Connection连接
conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
# 获得Cursor对象
cs1 = conn.cursor()
# 执行select语句,并返回受影响的行数:查询一条数据
count = cs1.execute('select id,name from goods where id>=4')
# 打印受影响的行数
print("查询到%d条数据:" % count)
# for i in range(count):
# # 获取查询的结果
# result = cs1.fetchone()
# # 打印查询的结果
# print(result)
# # 获取查询的结果
result = cs1.fetchall()
print(result)
# 关闭Cursor对象
cs1.close()
conn.close()
if __name__ == '__main__':
main()
View Code
3.3参数化
from pymysql import *
def main():
find_name = input("请输入物品名称:")
# 创建Connection连接
conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
# 获得Cursor对象
cs1 = conn.cursor()
# # 非安全的方式
# # 输入 " or 1=1 or " (双引号也要输入)
# sql = 'select * from goods where name="%s"' % find_name
# print("""sql===>%s<====""" % sql)
# # 执行select语句,并返回受影响的行数:查询所有数据
# count = cs1.execute(sql)
# 安全的方式
# 构造参数列表
params = [find_name]
# 执行select语句,并返回受影响的行数:查询所有数据
count = cs1.execute('select * from goods where name=%s', params)
# 注意:
# 如果要是有多个参数,需要进行参数化
# 那么params = [数值1, 数值2....],此时sql语句中有多个%s即可
# 打印受影响的行数
print(count)
# 获取查询的结果
# result = cs1.fetchone()
result = cs1.fetchall()
# 打印查询的结果
print(result)
# 关闭Cursor对象
cs1.close()
# 关闭Connection对象
conn.close()
if __name__ == '__main__':
main()
View Code
四、MySQL高级
4.1视图
1. 问题
对于复杂的查询,往往是有多个数据表进行关联查询而得到,如果数据库因为需求等原因发生了改变,为了保证查询出来的数据与之前相同,则需要在多个地方进行修改,维护起来非常麻烦
解决办法:定义视图
2. 视图是什么
通俗的讲,视图就是一条SELECT语句执行后返回的结果集。所以我们在创建视图的时候,主要的工作就落在创建这条SQL查询语句上。
视图是对若干张基本表的引用,一张虚表,查询语句执行的结果,不存储具体的数据(基本表数据发生了改变,视图也会跟着改变);
方便操作,特别是查询操作,减少复杂的SQL语句,增强可读性;
3. 定义视图
建议以v_开头
create view 视图名称 as select语句;
4. 查看视图
查看表会将所有的视图也列出来
show tables;
5. 使用视图
视图的用途就是查询
select * from v_stu_score;
6. 删除视图
drop view 视图名称; 例: drop view v_stu_sco;
7. 视图的作用
4.2事务
事务四大特性(简称ACID)
以下内容出自《高性能MySQL》第三版,了解事务的ACID及四种隔离级有助于我们更好的理解事务运作。
下面举一个银行应用是解释事务必要性的一个经典例子。假如一个银行的数据库有两张表:支票表(checking)和储蓄表(savings)。现在要从用户Jane的支票账户转移200美元到她的储蓄账户,那么至少需要三个步骤:
上述三个步骤的操作必须打包在一个事务中,任何一个步骤失败,则必须回滚所有的步骤。
可以用START TRANSACTION语句开始一个事务,然后要么使用COMMIT提交将修改的数据持久保存,要么使用ROLLBACK撤销所有的修改。事务SQL的样本如下:
一个很好的事务处理系统,必须具备这些标准特性:
一个事务必须被视为一个不可分割的最小工作单元,整个事务中的所有操作要么全部提交成功,要么全部失败回滚,对于一个事务来说,不可能只执行其中的一部分操作,这就是事务的原子性
数据库总是从一个一致性的状态转换到另一个一致性的状态。(在前面的例子中,一致性确保了,即使在执行第三、四条语句之间时系统崩溃,支票账户中也不会损失200美元,因为事务最终没有提交,所以事务中所做的修改也不会保存到数据库中。)
通常来说,一个事务所做的修改在最终提交以前,对其他事务是不可见的。(在前面的例子中,当执行完第三条语句、第四条语句还未开始时,此时有另外的一个账户汇总程序开始运行,则其看到支票帐户的余额并没有被减去200美元。)
一旦事务提交,则其所做的修改会永久保存到数据库。(此时即使系统崩溃,修改的数据也不会丢失。)
事务命令
表的引擎类型必须是innodb类型才可以使用事务,这是mysql表的默认引擎
查看表的创建语句,可以看到engine=innodb
-- 选择数据库
use jing_dong;
-- 查看goods表
show create table goods;
View Code
开启事务,命令如下:
begin;
或者
start transaction;
View Code
提交事务,命令如下
commit;
View Code
回滚事务,命令如下:
rollback;
View Code
注意
4.2.1提交
step1:连接
终端1:查询商品分类信息
select * from goods_cates;
step2:增加数据
终端2:开启事务,插入数据
begin;
insert into goods_cates(name) values('小霸王游戏机');
终端2:查询数据,此时有新增的数据
select * from goods_cates;
step3:查询
终端1:查询数据,发现并没有新增的数据
select * from goods_cates;
step4:提交
终端2:完成提交
commit;
step5:查询
终端1:查询,发现有新增的数据
select * from goods_cates;
View Code
4.2.2回滚
step1:连接
终端1
select * from goods_cates;
step2:增加数据
终端2:开启事务,插入数据
begin;
insert into goods_cates(name) values('小霸王游戏机');
终端2:查询数据,此时有新增的数据
select * from goods_cates;
step3:查询
终端1:查询数据,发现并没有新增的数据
select * from goods_cates;
step4:回滚
终端2:完成回滚
rollback;
step5:查询
终端1:查询数据,发现没有新增的数据
select * from goods_cates;
View Code
4.3索引
索引是什么
索引是一种特殊的文件(InnoDB数据表上的索引是表空间的一个组成部分),它们包含着对数据表里所有记录的引用指针。
更通俗的说,数据库索引好比是一本书前面的目录,能加快数据库的查询速度
索引的使用
show index from 表名;
create index 索引名称 on 表名(字段名称(长度))
drop index 索引名称 on 表名;
索引demo
1.创建测试表testindex
create table test_index(title varchar(10));
2. 使用python程序(ipython也可以)通过pymsql模块 向表中加入十万条数据
from pymysql import connect
def main():
# 创建Connection连接
conn = connect(host='localhost',port=3306,database='jing_dong',user='root',password='mysql',charset='utf8')
# 获得Cursor对象
cursor = conn.cursor()
# 插入10万次数据
for i in range(100000):
cursor.execute("insert into test_index values('ha-%d')" % i)
# 提交数据
conn.commit()
if __name__ == "__main__":
main()
3. 查询
开启运行时间监测:
set profiling=1;
查找第1万条数据ha-99999
select * from test_index where title='ha-99999';
查看执行的时间:
show profiles;
为表title_index的title列创建索引:
create index title_index on test_index(title(10));
执行查询语句:
select * from test_index where title='ha-99999';
再次查看执行的时间
show profiles;
例子
注意:
要注意的是,建立太多的索引将会影响更新和插入的速度,因为它需要同样更新每个索引文件。对于一个经常需要更新和插入的表格,就没有必要为一个很少使用的where字句单独建立索引了,对于比较小的表,排序的开销不会很大,也没有必要建立另外的索引。
建立索引会占用磁盘空间