視圖: 本質上是一種虛拟表,其内容與真實表相似,包含一系列帶有名稱的列和行資料。
視圖的特點如下:
- 視圖的列可以來自不同的表,是表的抽象和在邏輯意義上建立的新關系。
- 視圖是由基本表(實表)産生的表(虛表)。
- 視圖的建立和删除不影響基本表。
- 對視圖内容的更新(添加、删除和修改)直接影響基本表。
- 建立視圖
# 建立資料庫
create database view;
# 使用資料庫
use view;
# 建立表
create table t_product(
id int primary key,
name varchar(20),
price float
);
# 檢視目前表中的資料
select * from t_product;
# 建立視圖
create view view_selectproduct
as
select id,name from t_product;
# 使用視圖--實質是将語句進行了封裝
select * from view_selectproduct;
-
建立各種視圖
(1)封裝實作查詢常量語句的視圖, 即所謂常量視圖。
create view view_test1
as
select 3.1415926;
(2)封裝使用聚合函數(SUM、MIN、MAX、COUNT等)查詢語句
create view view_test2
as
select count(name) from t_student;
(3) 封裝實作排序功能(ORDER BY)查詢語句的視圖
create view view_test3
as
select name from t_product order by id desc;
(4) 封裝實作表内連接配接查詢語句的視圖
create view view_test4
as
select s.name
from t_student as s, t_group as g
where s.group_id=g.id
and g.id=2;
(5)封裝實作表外連接配接(LEFT JOIN 和 RIGHT JOIN)查詢語句的視圖。
create view view_test5
as
select s.name
from t_student as s
left join
t_group as g
on s.group_id=g.id
where g.id=2;
(6)封裝實作子查詢相關查詢語句的視圖。
create view view_test6
as
select s.name
from t_student as s
where s.group_id in (
select id from t_group
);
(7)封裝了實作記錄聯合(UNION和UNION ALL)查詢語句視圖
create view view_test7
as
select id, name from t_student
union all
select id, name from t_group;
-
檢視視圖
(1)SHOW TABLES語句檢視視圖名
(2)SHOW TABLE STATUS語句檢視視圖詳細資訊show tables;
或show table status \G;
show table status from view \G;
(3)SHOW CREATE VIEW語句檢視視圖定義資訊show table status from view like "view_selectproduct" \G;
(4)DESCRIBE|DESC語句檢視視圖設計資訊show create view view_selectproduct \G;
desc view_selectproduct;
- 删除視圖
drop view view_selectproduct,view_select_selectproduct1;
- CREATE OR REPLACE VIEW語句修改視圖
# 修改視圖語句
create or replace view view_selectproduct
as
select name from t_product;
# 查詢視圖
select * from view_selectproduct;
- ALERT 語句修改視圖
alter view view_selectproduct
as
select id,name from t_product;