视图
视图(view
)是一种虚拟存在的表,是一个逻辑表,本省没有数据,内容由查询定义。
基表:用来创建视图的表叫做基表
通过视图,我们可以查看基表的部分数据。视图数据来自定义视图的查询中使用的表,使用动态图动态生成。
优点
- 简单
- 安全
- 数据独立
语法
create view <视图名> as <select语句>
案例
create view view_learn as select (
A.student_id from (
select student_id, num from score where course_id = 1
) as A left join (
select student_id, num from score where course_id = 2
) as B on A.student_id = B.student_id
where A.num > if (isnull(B.num), 0, B.num)
);
流程控制
IF
if condition then
...
elseif condition then
...
else
...
end if
CASE
case value
when value then ...
when value then ...
else ...
end case
WHILE
while condition do
...
end while
LEAVE
-- 相当于break
leave label;
示例
-- leave语句退出循环或程序,只能和BEGIN ... END,LOOP,REPEAT,WHILE语句配合使用
-- 创建存储过程
delimiter //
create procedure example_leave(out sum int)
begin
declare i int default 1;
declare s int default 0;
while_label:while i <= 100 do
set s = s + i;
set i = i + 1;
if i = 50 then
leave while_label;
end if;
end while;
set sum = s;
end //
delimiter ;
call example_leave(@sum);
select @sum;
ITERATE
-- 相当于 continue
iterate label;
LOOP
-- 相当于 while(true){}
loop
...
end loop
-- 可以用LEAVE退出循环
示例
-- 创建存储过程
delimiter //
create procedure example_loop(out sum int)
begin
declare i int default 1;
declare s int default 0;
loop_label:loop
set s = s + i;
set i = i + 1;
if i > 100 then
leave loop_label;
end if;
end loop;
set sum = s;
end
//
delimiter ;
call example_loop(@sum);
select @sum;
REPEAT
-- 相当于 do ... while(condition)
REPEAT
...
UNTIL condition
END REPEAT
示例
delimiter //
create procedure example_repeat(out sum int)
begin
declare s int default 1;
declare i int default 0;
repeat
set s = s + i;
set i = i + 1;
until i > 100
end repeat;
set sum = s;
end
//
delimiter ;
call example_repeat(@sum);
select @sum;
推荐课程:https://xxetb.xetslk.com/s/3oyV5o