Mysql索引、事务、视图 常用命令及要点归纳

索引:

一种快速定位技术,相当于一本书的目录页.

作用:快速查询数据 条件:数据条目大于2000条

create index id_index on info (id); //创建普通索引

show index from info \G //查看索引

drop index id_index from on info; //删除索引

create unique index unique_id_index on info (id); //创建唯一索引

alter table info add primary key (id); //创建主键索引(已经创建了表,没有指定主键,然后修改表加入主键,主键索引会自动创建)

alter table info change id id int(10);//删除自增长

alter table info drop primary key;//删除主建

alter table info add column age int; //添加列

alter table info drop column age int; //删除列

create table infos (descript TEXT,FULLTEXT(descript)); //创建全文索引

create index multi_index on info(name,address); //创建多列索引

事务:

一组操作共同执行或者都不执行,结果保持一致。

特性:原子性、一致性、隔离性、持久性。

例如:银行转账

姓名 余额 条件:余额>0
Zhangsan 100 /
lisi 200 /

注:Zhangsan 转账100给 to lisi

事务固定格式:

begin 开始
Update bank set money=money+100 where name=’lisi’
Update bank set money=money-100 where name=’zhangsan’
commit 提交
rollback 回滚

补充:

set autocommit = 1; //开启自动提交

set autocommit = 0; //禁止自动提交

savepoint s2; //定义回滚点

rollback to savepoint s2; //回滚到S2 (相当于虚拟机还原快照)

视图:

视图是 数据库中的虚拟表。

作用:一张表中的数据给不同的权限用户提供访问

举例:公司员工绩效工资考核表:

工号 姓名 年龄 岗位 绩效 工资
1 Tom 50 总裁 / 100万
2 Jerry 40 总监 90 20万
3 charry 30 云计算工程师 80 12万
4 Jack 24 云计算工程师 90 15万

语法: create view 视图名称 AS select 语句

create view scoreview as select from info where score > 80; //创建视图(条件:成绩>80)

select * from score_view; //查看视图

update score_view set score=88 where id=1; //id1的成绩更新为88

drop view if exists score_view; //删除视图

总结:

1.数据库索引分为普通索引、唯一性索引、主键索引、全文索引、多列索引;

2.数据库索引可以协助快速查询表中数据,但并不是任何字段都需要创建索引;

3.数据库事务的ACID特性:原子性、一致性、隔离性、持久性;

4.MySQL事务命令有begin、rollback、commit、savepoint;

猜你喜欢

转载自blog.51cto.com/13721050/2165610