create view 视图名称 as select 语句;
create or replace view course_v_1 as
select name from course where name = 'MySQL';
查看创建视图语句:show create view 视图名称;
查看视图数据:select * from 视图名称;
show create view course_v_1;
select * from course_v_1;//视图查询也可以加上where条件
方式一:create or replace view 视图名称 as select 语句;
方式二:alter view 视图名称 as select 语句;
create or replace view course_v_1 as
select id,name from course where name = 'MySQL';
alter view course_v_1 as
select id,name from course where name = 'MySQL';
drop view [if exist]视图名称;
drop view if exists course_v_1;
insert into 视图名字 values (字段值,字段值);
create or replace view 视图名称 as select 语句 with cascaded/local check option;
create or replace view course_v_1 as
select id,name from course where id <=20
with cascaded check option;
-- 创建视图
create or replace view course_v_1 as
select id,name from course where id <=20;
create or replace view course_v_2 as
select id,name from course_v_1 where id >=10
with cascaded check option;
-- 插入数据
insert into course_v_2 values (6,'Airflow');
insert into course_v_2 values (25,'GO');
insert into course_v_2 values (15,'VB');
-- 创建视图
create or replace view course_v_1 as
select id,name from course where id <=20;
create or replace view course_v_2 as
select id,name from course_v_1 where id >=10
with cascaded check option;
create or replace view course_v_3 as
select id,name from course_v_2 where id <=15;
insert into course_v_3 values (11,'Python');
insert into course_v_3 values (17,'Python');
insert into course_v_3 values (28,'Python');
create or replace view course_v_count as
select COUNT(*) from course;
-- 执行失败,报错:不可执行插入操作
insert into course_v_count values(11);
[HY000][1471] The target table course_v_count of the INSERT is not insertable-into
create or replace view tb_user_view as
select
id,name,profession,age,gender,status,createtime
from
tb_user;
-- 后续直接查询视图
select * from tb_user_view;
create view tb_stu_course as
select
s.name studentname,s.no student_no,c.name course_name
from
student s ,student_course sc,course c
when
s.id = sc.studentid
and
sc.courseid = c.id;
-- 后续直接查询视图
select * from tb_stu_course;
create procedure 存储过程名称([参数列表])
begin
-- SQL语句
end;
create procedure p1()
begin
select count(*) from tb_user;
end;
-- 因为命令行中见到分号默认结束,因此先定义结束符
mysql> delimiter $$
mysql> create procedure p1()
mysql> begin
mysql> select count(*) from tb_user;
mysql> end
mysql>$$
call 名称([参数]);
call p1();
select * from information_schema.ROUTINES
where ROUTINE_SCHEMA = 'itcast';
-- information_schema是库,routines是表,routine_schema是字段
select * from information_schema.routines where routine_schema = 'xxx';
show create procedure p1;
drop procedure [if exist] 存储过程名称;
show [session/global] variables; --查看所有系统变量
show [session/global] variables like '......' -- 可以通过like模糊匹配方式查找变量
select @@[session/global] 系统变量名 -- 查看指定变量的值
show session variables;
show session variables like 'auto%';
select @@session.autocommit;
set [session/global] 系统变量名 = 值;
set @@[session/global] 系统变量名 = 值;
set session autocommit = 0;
set @@session.autocommit = 0;
set @@global.autocommit = 0;
select @@global.autocommit;
set @变量名 = 值;
set @变量名 := 值;
select @变量名 := 值;
select 字段名 into @变量名 from 表名;
set @myname = '芬芬';
set @myage := '18';
set @mygender := '女',@myhobby:='大数据';
select @mycolor := 'red';
select COUNT(*) into @mycount from tb_user;
select @变量名;
select @myname,@myage,@mygender,@myhobby;
select @mycolor,@mycount;
-- 就算没赋值,也可以查,就是0而已
select @abc;
declare 变量名 变量类型[default...];
变量类型有:int,bigint,char,varchar,date,time等
set 变量名 = 值;
set @变量名 := 值;
select @变量名 := 值;
-- 声明
-- 赋值
create procedure p2()
begin
declare course_count int default 0;
set course_count :=100;
select course_count;
end;
-- 调用
call p2();
if 条件1 then
...
elseif 条件2 then
...
else
...
end if;
create procedure p3 ()
begin
declare score int default 58;
declare result varchar(10);
if score >= 85 then
set result := '优秀';
elseif score >= 60 then
set result := '及格';
else
set result := '不及格';
end if;
select result;
end;
call p3();
见下章5.5 参数的传参写法
create procedure 存储构成名称(in/out/inout 参数名 参数类型)
begin
--sql语句
end;
create procedure p4 (in score int,out result varchar(10))
begin
-- declare score int default 58;
-- declare result varchar(10);
if score >= 85 then
set result := '优秀';
elseif score >= 60 then
set result := '及格';
else
set result := '不及格';
end if;
-- select result;
end;
-- 第二个参数需要一个变量来接收,然后打印出来
call p4(68,@result);
select @result;
将传入的200分制的分数,进行换算,换算成百分制,然后返回分数
分析:分数即使传入值,也是传出值,用inout
create procedure p5 (inout score int)
begin
set score := score * 0.5;
end;
set @score := 178; -- 初始化
call p5(@score); -- 调用
select @score; -- 打印
case 字段
when 条件 then 程序
when 条件 then 程序
else 程序
end case;
create procedure p6(in month int)
begin
declare result varchar(10);
case
when month >=1 and month <=3 then
set result = '第一季度';
when month >=4 and month <=6 then
set result = '第二季度';
when month >=7 and month <=9 then
set result = '第三季度';
when month >=10 and month <=12 then
set result = '第四季度';
else
set result:= '非法参数';
end case;
select concat('你输入的月份为',month,'所属的季度为',result);
end;
call p6(4);
while 条件 do
SQL逻辑
end while;
create procedure p7 (in n int)
begin
declare total int default 0;
while n > 0 do
set total:= total + n;
set n := n - 1;
end while;
select total ;
end;
call p7(10);
repeat
SQL逻辑
until 条件
end repeat;
create procedure p8(in n int)
begin
declare total int default 0;
repeat
set total:= total+n;
set n:=n-1;
until n<=0
end repeat;
select total;
end;
call p8(10);
call p8(100);
如果不在SQL逻辑中增加退出循环的条件,可以用来实现简单的死循环,LOOP一般配合
begin_label :LOOP
SQL逻辑
END LOOP end_label;
create procedure p9(in n int)
begin
declare total int default 0;
sum:loop
if n<=0 then
leave sum;
end if;
set total:=total + n;
set n := n-1;
end loop sum;
select total;
end;
call p9(10);
call p9(100);
create procedure p10(in n int)
begin
declare total int default 0;
sum:loop
if n<=0 then
leave sum;
end if;
if n%2 = 1 then
set n := n-1; -- 这部是因为奇数的时候回跳过下面的n-1,因此上面也减一次
iterate sum;
end if;
set total:=total + n;
set n := n-1;
end loop sum;
select total;
end;
call p10(10);
call p10(100);
概念:是用来存储查询结果集的数据类型,在存储过程和函数中可以使用游标对结果集进行循环的处理。
内容:游标的声明、OPEN、CLOSE
declare 游标名 cursor for 查询语言;
open 游标名;
fetch 游标名 into 变量;
close 游标名;
create procedure p11(in uage int)
begin
-- 声明两个变量,方便后续赋值,普通变量声明要在声明游标之前
declare uname varchar(100);
declare upro varchar(100);
-- 声明游标
declare u_cursor cursor for select name,profession from tb_user where age <= uage; -- 逻辑写这边
-- 创建一张表
drop table if exists tb_user_pro;
create table if not exists tb_user_pro(
id int primary key auto_increment,
name varchar(100),
profession varchar(100)
);
-- 打开游标
open u_cursor;
-- 获取游标记录
-- 循环遍历集合并赋值
while true do
fetch u_cursor into uname,upro;
-- 插入表结构
insert into tb_user_pro values(null,uname,upro);-- null是自增的id,不用慌
end while;
-- 关闭游标
close u_cursor;
end;
概念
可以用来定义在流程控制结构执行构成中遇到问题时相应的处理步骤,类比异常处理
语法
declare handler_action HANDLER FOR condition_value [condition_value]...statment;
handler_action:
continue:继续执行当前程序
exit:终止执行当前程序
condition_value:
如下图一部分,如有兴趣去MySQL官方文档那边看下各个状态码的用途
create procedure p11(in uage int)
begin
-- 声明两个变量,方便后续赋值,普通变量声明要在声明游标之前
declare uname varchar(100);
declare upro varchar(100);
-- 声明游标
declare u_cursor cursor for select name,profession from tb_user where age <= uage;
-- 声明handler
declare exit handler for SQLSTATE '02000' close u_cursor;
-- 也可以 declare exit handler for not found close u_cursor;表示处理02开头的状态码
-- 创建一张表
drop table if exists tb_user_pro;
create table if not exists tb_user_pro(
id int primary key auto_increment,
name varchar(100),
profession varchar(100)
);
-- 打开游标
open u_cursor;
-- 获取游标记录
-- 循环遍历集合并赋值
while true do
fetch u_cursor into uname,upro;
-- 插入表结构
insert into tb_user_pro values(null,uname,upro);
end while;
-- 关闭游标
close u_cursor;
end;
call p11(40);
create function 存储函数名称[参数列表]
returns type [参数]
begin
--SQL语句
return...;
end;
参数:
deterministic:相同的输入参数总是产生相同的结果
no sql:不包含SQL
read sql data:包含读取数据的语句,但不包含
create function fun1(n int )
returns int deterministic
begin
declare total int default 0;
while n>0 do
set total:=total+n;
set n := n-1;
end while;
return total;
end;
select fun1(100);
触发器是与表有关的数据库对象,指在insert/update/delete之前或之后,触发并执行触发器中定义的SQL语句集合
可以协助应用在数据库段确保数据的完整性,日志记录,数据校验等操作。
使用别名OLD和NEW来引用触发器中发生变化的记录内容
create trigger trigger_name
before/after/ insert/update/delete --指定类型触发器
on tbl_name for each row --行级触发器
begin
trigger_stmt;
end
show triggers;
drop trigger trigger_name;
通过触发器记录tb_user的数据的变更日志,将变更日志插入到日志表user_logs表中,包含增,改,删
create table user_logs(
id int(11) not null auto_increment,
operation varchar(20) not null comment '操作类型, insert/update/delete',
operate_time datetime not null comment '操作时间',
operate_id int(11) not null comment '操作的ID',
operate_params varchar(500) comment '操作参数',
primary key(`id`)
)engine=innodb default charset=utf8;
-- 插入数据时的触发器
create trigger tb_user_insert_trigger
after insert on tb_user for each row
begin
insert into user_logs(id, operation, operate_time, operate_id, operate_params) values
(null,'insert',now(),new.id,-- null 表示默认id自增
concat('插入数据的内容为:id=',NEW.id,',name=',new.name,',phone=',new.phone,',email=',new.email,',profession=',new.profession));
end;
show triggers ;
insert into tb_user(id, name, phone, email, profession, age, gender, status, createtime)
VALUES (25,'二皇子','18809091212','[email protected]','软件工程',23,'1','1',now());
-- 和insert触发器不同的点是:
create trigger tb_user_update_trigger
after update on tb_user for each row
begin
insert into user_logs(id, operation, operate_time, operate_id, operate_params) values
(null,'update',now(),new.id,-- null 表示默认id自增
concat('更新之前的数据:id=',OLD.id,',name=',OLD.name,',phone=',OLD.phone,',email=',OLD.email,',profession=',OLD.profession,
'|更新之后的数据:id=',NEW.id,',name=',new.name,',phone=',new.phone,',email=',new.email,',profession=',new.profession));
end;
show triggers ;
update tb_user set age = 20 where id = 23;
update tb_user set age = 20 where id <= 5; -- 因为是行级触发器,所以回触发5次
-- 删除数据时的触发器
create trigger tb_user_delete_trigger
after delete on tb_user for each row
begin
insert into user_logs(id, operation, operate_time, operate_id, operate_params) values
(null,'delete',now(),OLD.id,-- null 表示默认id自增
concat('更新之前的数据:id=',OLD.id,',name=',OLD.name,',phone=',OLD.phone,',email=',OLD.email,',profession=',OLD.profession));
end;
show triggers ;
delete from tb_user where id = 25;