1.创建视图
create view 视图名(视图列1,视图列2) 视图列名为中文
as
select * from 表名 没有指定那一列,从第一个列名开始创建
with check option;
2.添加视图数据、删除视图、查询视图、修改视图
和表一样的用法
3.创建多表视图
create view 视图名(视图列1,视图列2,视图列3)
as
select 列名1,列名2,列名3 from 表名1 表名1别名 left join 表名2 表名2别名 on 表名1列名=表名2列名;
例:
create view v_a_b(姓名,标题,内容)
as
select a.author_name,b.title,b.content form author a left join blog b on b.author_id=a.id;
4.修改视图 有就修改,没有就替换
create or replace view v_blog(编号,标题,内容,作者编号)
as select * from blog where author_id=1 as是连接,视图只存储author_id=1的数据
with check option; 这一行表示where条件约束
5.回滚和提交 以数字的顺序来执行实现回滚
开启事务 1
begin;
插入语句 2
insert into b(id)value('5');
提交事务 提交后不能回滚
commit;
回滚
rollback; 4
查询
select * from b; 3 5
6.触发器
#学生表
CREATE TABLE student(
username VARCHAR(20),
PASSWORD VARCHAR(20),
stuid INT PRIMARY KEY AUTO_INCREMENT,
birthday DATE
);
INSERT INTO student(username,PASSWORD,birthday)VALUES
('王二','111111','2016-08-23'),
('李四','123456','2016-07-23'),
('杨三','123456','2016-08-17'),
('刘五','000000','2016-08-18'),
('黄六','666666','2016-08-23');
#成绩表
CREATE TABLE IF NOT EXISTS cj(
NUMBER INT,
stu_id INT,
stu_name VARCHAR(20),
math FLOAT,
chinese FLOAT,
english FLOAT
);
#触发器方式1
create trigger ins_stu
after insert on student for each row
insert into cj(number,stu_id,stu_name,math,chinese,english)
values(1,new.stuid,new.username,88,77,99);
#触发器方式2
delimiter $
create trigger ins_stu
after insert on student for each row
begin
insert into cj(number,stu_id,stu_name,math,chinese,english)
values(1,new.stuid,new.username,88,77,99); new表示student表
end $
delimiter ;
#执行触发过程
insert into student(username,password,birthday)values
('张三','22222','2016-08-23');
7.创建存储过程
delimiter $
create procedure test2()
begin
#声明变量类型
declare un varchar(32) default '';
#给un变量赋值
set un='xiaoxiao';
#将student表的数据复制给un,复制的是student表username列的数据,条件是student表的stuid=3的username列数据
select username into un from student where stuid=3;
#查询un变量,返回
select un;
end $
delimiter ;
#调用存储过程
call test2();
创建存储过程2 两张表会显示两个结果
delimiter $
create procedure testa()
begin
select * from student;
select * from cj;
end $
delimiter ;
声明变量类型两次
delimiter $
create procedure test3()
begin
begin
declare un varchar(32) default '';
set un='xiaoxiao';
select username into un from student where stuid = 3;
select un;
end;
begin
declare un varchar(32) default '';
set un='xiaoxiao';
select username into un from student where stuid = 5;
select un;
end;
end $
declimiter ;