数据库对象
表
数据字典(系统表):存放数据库相关信息的表
约束:执行数据校验的规则,保证数据完整性
视图:表中数据的逻辑显示
索引:提高查询性能
存储过程:完成一次完整的业务处理
存储函数:完成一次特定的计算
触发器:事件监听器
视图是一种虚拟表,只是一种视图,对基表的数据的展示,自身并不存数据。
视图的创建和删除只影响自身,不影响对应的基表。
当对视图插入,删除,修改数据时,基表中的数据会相应的发生变化。
create view vu_emp
as
select employee_id,last_name,salary from employees;
select * from vu_emp;
# 查看表和视图
show tables;
# 查看视图结构
desc xxx;
# 查看视图属性信息
show table status like 'xxx'\G
show create view xxx;
# 修改视图
create or replace view vu_emp
as
select xxx;
# 或者
alter view vu_emp
as
select xxx;
# 删除视图
drop view xxx;
drop view if exists xxx;
存储过程
# 无参,无返回值的
delimiter $
create procedure store_process()
begin
select * from employees;
end $
delimiter ;
# 调用
call store_process();
# 有返回值的
delimiter $
create procedure store_process2(out ms double)
begin
select min(salary) into ms from employees;
end $
delimiter ;
# 调用(结果放到了ms变量里)
call store_process2(@ms);
select @ms;
# 另一个例子
delimiter $
create procedure store_process3(in empname varchar(20))
begin
select salary from employees
where last_name = empname;
end $
delimiter ;
# 调用
call store_process3('Abel');
存储函数
# 一定有返回值
# 参数都是in
# 示例
delimiter $
create function functionq()
returns varchar(25)
begin
return (select email from employees where last_name = 'Abel');
end $
delimiter ;
# 调用
select functionq();
# 另一个例子
delimiter $
create function functionR(emp_id int)
returns varchar(25)
begin
return (select email from employees where employee_id = emp_id);
end $
delimiter ;
# 调用
select functionR(101);
# 存储函数和存储过程的信息存储在information_schema数据库下的Routines表中
select * from information_schema.routines
where routine_name = 'xxx' and routine_type = 'PROCEDURE|FUNCTION';
#存储过程和函数存在同名的,需指定routine_type
drop function if exists xxx;
drop procedure if exists xxx;
# 存储过程只在创建时进行编译,之后的使用都不需要编译
# 封装成了模块
变量
# 系统变量
全局系统变量global
会话系统变量session
默认是会话级别(session)
show global variables;
show session variables;
# 查看指定系统变量
# 系统变量以两个@开头
# 不指定全局或会话,先在会话系统变量中找,然后在全局中找
select @@global.xxx;
select @@session.xxx;
select @@xxx;
# 修改系统变量的值
# 方式1:修改配置文件,重启服务
# 方式2
set @@global.xxx = newVal;
set global xxx = newVal;
# 重启mysql服务会失效,仅针对当前实例
# 自定义变量
# 以@开头
# 分为会话和局部
# 会话针对当前连接,局部针对存储过程和存储函数
# 定义
set @xxx = val;
select @count := count(*) from employees;
select @count;
select avg(salary) into @ajk from employees;
select @ajk;
# 查看
select @xxx;