mysql 5. 0.1版本出现的新特性,本身是一个虚拟表, 它的数据来自于表,通过执行时动态生成。
create
view视图名
as
查询语句;
举例:
USE myemployees;
#1.查询邮箱中包含a字符的员工名、部门名和工种
#创建
CREATE VIEW myv1
AS
SELECT e.last_name,d.department_name,j.job_title
FROM employees e
JOIN departments d ON e.department_id = d.department_id
JOIN jobs j ON e.job_id = j.job_id;
#使用
SELECT * FROM myv1 WHERE last_name LIKE'%a%';
方式一创建修改:
create or replace view 视图名
as
查询语句;
方式二修改:
alter view视图名
as
查询语句
drop view视图1,视图2....
desc视图名;
或
SHOW CREATE VIEW 视图名;
更新
UPDATE myv6 SET salary=10000 WHERE last_name='k_ing';
1.插入
insert
2.修改
update
3.删除
delete
4.查看
select
举例
CREATE OR REPLACE VIEW vw1
AS
SELECT last_name, email
FROM employees;
#1.插入
INSERT INTO vw1 VALUES('小明','[email protected]');
#2.修改
UPDATE vw1 SET last_name = 'xiaoming' WHERE last_name='小明';
#3.删除
DELETE FROM vw1 WHERE last_name = 'xiaoming';
注意:视图一般用于查询的,而不是更新的,所以具备以下特点的视图都不允许更新
分组函数 \ GROUP BY\ HAVING \UNION \UNION ALL
CREATE OR REPLACE VIEW myv4
AS
SELECT last_name, department_name
FROM employees e
JOIN departments d
ON e.department_id = d.department_id;
CREATE OR REPLACE VIEW myv2
AS
SELECT 'john' NAME;
SELECT *
FROM myv2;
CREATE OR REPLACE VIEW myv6
AS
SELECT last_name, email, salary
FROM employees
WHERE employee_id IN (
SELECT manager_id
FROM employees
WHERE manager_id IS NOT NULL
);
CREATE OR REPLACE VIEW myv5
AS
SELECT * FROM myv3;
可以通过以下两种方式来删除主表的记录
ALTER TABLE stuinfo ADD CONSTRAINT fk_ stu_ major FOREIGN KEY (majorid) REFERENCES major(id) ON DELETE CASCADE;
ALTER TABLE stuinfo ADD CONSTRAINT fk_ stu_ major FOREIGN KEY (majorid) REFERENCES major(id) ON DELETEI SET NULL;
关键字 是否占用物理空间 使用
视图 create view 占用较小,只保存sql逻辑 一般用于查询,一般不能增删改表
表 create table 保存实际的数据 增删改查