索引
此时是要获取所有的数据,是否有索引作用不大
select * from emp
– 因为数据库以及自动的给主键列empno创建了索引,查询条件中出现empno,自动使用索引进行查询
– 是否使用索引,语句没有区别
select * from emp where empno = 7654;
– 因为没有给ename列创建索引,此时是逐个查询比较,效率低下
select * from emp where ename = ‘BLAKE’
– 创建一个索引,默认升序排列
create index index_emp_ename on emp(ename)
– 因为已经创建了索引,所以此时使用索引进行查询,效率提升
select * from emp where ename = ‘BLAKE’
– 显示索引
show index from emp;
– 删除索引
drop index index_emp_ename on emp
alter table emp drop index index_emp_ename
– 没有给sal、hiredate创建索引,效率低下
select * from emp order by sal ,hiredate
– 创建索引
create index index_emp_sal_hiredate on emp (sal ,hiredate desc)
– 使用索引,效率提升
select * from emp order by sal ,hiredate
事务
– 创建account账户表
create table account(
id int primary key auto_increment,
username varchar(30) not null,
balance double
);
– 为account账户表同时插入两条数据
insert into account (username, balance) values(‘张三’, 2000),(‘李四’, 2000);
– 查看account账户表中的数据
select * from account;
– 转账操作
– 默认事务自动提交,一条dml语句是一个事务
update account set balance= balance-1000 where id =1
update account set balance = balance +1000 where id=2
– 如果要多个操作是一个事务,需要事务必须手动的提交
– 事务开始,成功不会自动提交,失败也不会自动回滚
start transaction
update account set balance= balance-1000 where id =1
update account set balance = balance1 +1000 where id=2
– 手动提交
commit
– 手动回滚
rollback;
mysql 查询、设置事务隔离级别 transaction_isolation
select @@transaction_isolation
– 设置当前会话的事务级别为 READ-COMMITTED
set session transaction isolation level read uncommitted
set session transaction isolation level read committed
set session transaction isolation level repeatable read
set session transaction isolation level read uncommitted
select * from dept
视图
– 创建单表视图
create or replace view myview1
as
select empno,ename,job,mgr,hiredate,deptno from emp
where hiredate <‘1981-09-28’
with check option
select * from myview1
select empno,ename,job from myview1 where job =‘MANAGER’
insert into myview1 values(9999,‘9999’,‘9999’,7839,‘1980-12-23’,30)
– 1369 - CHECK OPTION failed ‘mydb.myview1’
insert into myview1 values(1000,‘9999’,‘9999’,7839,‘1999-12-23’,30)
select * from emp
– 创建多表视图
create or replace view myview2
as
select e.empno,e.ename,e.sal,e.comm,d.deptno,d.dname
from emp e
join dept d
on e.deptno = d.deptno
where sal>2500
select * from myview2
– 创建统计视图
create or replace view myview3
as
select e.deptno 部门编号, d.dname 部门名称,avg(sal) 平均工资,max(sal) 最高工资,count(*) 部门人数
from emp e
join dept d
using(deptno)
where deptno is not null
group by e.deptno
select * from myview3
– 创建基于视图的视图
create or replace view myview4
as
select * from myview3 where 最高工资>=3000
select * from myview4