视图
-- 创建视图
create view v_student AS
select name 姓名,age 年龄 from student;
-- 查询视图
select * from v_student;
结果:
姓名 年龄
诸葛亮 20
甄宓 18
事务
手动执行事务(一步一步执行,正常最后执行commit,遇到异常执行rollback;
-- 正常情况
begin;
update account set account=account-100 where name='大乔';
update account set account=account+100 where name='小乔';
commit;
-- 另一种写法
start transaction;
update account set account=account-100 where name='大乔';
update account set account=account+100 where name='小乔';
commit;
select * from account;
-- 异常情况(账户余额不能为负数)
begin;
update account set account=account-100 where name='大乔';
update account set account=account+100 where name='小乔';
-- insert 语句 into可以省略
insert account(name,account) VALUES('孙尚香',-1000);
ROLLBACK;
select * from account;
索引
创建索引
-- 创建表时同时添加索引(三种方式)
drop table if exists test_index;
create table test_index(
id int UNSIGNED PRIMARY key,
name VARCHAR(10) unique,
age int,
key(age)
);
-- 查看索引
show index from test_index;
结果:
Table Non_unique Key_name Seq_in_index Column_name ...
test_index 0 PRIMARY 1 id ...
test_index 0 name 1 name ...
test_index 1 age 1 age ...
-- 存储过程批量插入数据
drop procedure if EXISTS batch_insert;
create procedure batch_insert()
BEGIN
DECLARE maxNum int default 100000;
declare startNum int DEFAULT 0;
while startNum < maxNum DO
INSERT into test(id,topic) values(startNum+1,CONCAT('标题',startNum+1));
set startNum = startNum + 1;
end while;
end;
-- 清空表中数据
delete from test;
-- 调用存储过程插入数据
call batch_insert();
-- 开启运行时间监测(设置为0不再监测,重新登录后重置)
set profiling=1;
-- 查询(添加索引之前)
select * from test where topic='标题10001';
show profiles;
-- 添加索引
alter table test drop index index_topic;
-- 或者
drop index index_topic on test;
-- varchar类型长度要与字段长度一致
create index index_topic on test(topic(30));
-- 查看索引
show index from test;
-- 查询(添加索引之后,要用不同的查询条件,同样的查询条件数据库有优化查询的机制)
select * from test where topic='标题10002';
show profiles;
结果:
+----------+------------+--------------------------------------------+
| Query_ID | Duration | Query |
+----------+------------+--------------------------------------------+
| .. | .. | .. |
| 19 | 0.23813500 | select * from test where topic='????10001' |
| 20 | 1.04702000 | create index index_id on test(topic(30)) |
| 21 | 0.13929950 | select * from test where topic='????10002' |
| 22 | 0.00035150 | select * from test where topic='????10002' |
| 23 | 0.00089025 | select * from test where topic='????10005' |
| 24 | 0.01446350 | select * from test where topic='????10099' |
+----------+------------+--------------------------------------------+