MYSQL必知必会

MYSQL必知必会

高级

视图
视图的优点
  • 重用sql语句
  • 简化复杂的SQL操作
  • 保护数据
  • 更改数据格式和表示,视图可返回与底层表的格式不同的数据
视图的限制
  • 命名必须唯一
  • 视图可以嵌套
  • order by可以用在视图中,但是如果视图检索数据select中含有order by,那么视图中的order by也将被覆盖
  • 视图不能索引,也不能有关联的触发器
  • 视图可以和表一起使用
1
2
3
4
5
6
7
8
9
10
create view productcustomers as
select cust_name, cust_contact, prod_id from customers, orders, orderitems
where customers.cust_id = orders.cust_id and orderitems.order_num = orders.order_num;

# 查看视图创建语句
show create view productcustomers;
# 删除视图
drop view productcustomers;
# 更新视图
create or replace view as xxx
存储过程
1
2
3
4
5
6
7
8
create procedure customer_age()
begin
select avg(age) as age_avg from customer;
end;
# 使用存储过程
call customer_age();
# 删除存储过程
drop procedure customer_age;

带参数的存储过程

1
2
3
4
5
6
7
8
create procedure ordertotal(in onumber INT, out ototal DECIMAL(8, 2))
begin
select sum(item_price * quantity) from orderitems where order_num = onumber into ototal;
end;
# 调用存储过程
call ordertotal(2005, @total);
# 之后再进行查询
select @total;
事务处理
1
2
3
4
5
6
select * from customer;
start transaction;
delete from customer;
select * from customer;
rollback;
select * from customer;

在事务处理块中,提交不会隐含地进行,进行明确的提交,需要使用commit语句

1
2
3
start transaction;
delete from orders where order_num = 20010;
commit;

为了支持回退部分事务处理,可以设置保留点

1
2
savepoint delete1;
rollback to delete1;

MYSQL必知必会
http://xrcol.github.io/2024/04/05/3c20485d3d9a/
作者
XR
发布于
2024年4月5日
许可协议