視圖: 本質(zhì)上是一種虛擬表,其內(nèi)容與真實(shí)表相似况褪,包含一系列帶有名稱的列和行數(shù)據(jù)通熄。
視圖的特點(diǎn)如下:
- 視圖的列可以來自不同的表,是表的抽象和在邏輯意義上建立的新關(guān)系脱羡。
- 視圖是由基本表(實(shí)表)產(chǎn)生的表(虛表)萝究。
- 視圖的建立和刪除不影響基本表。
- 對視圖內(nèi)容的更新(添加轻黑、刪除和修改)直接影響基本表糊肤。
- 創(chuàng)建視圖
# 創(chuàng)建數(shù)據(jù)庫
create database view;
# 使用數(shù)據(jù)庫
use view;
# 創(chuàng)建表
create table t_product(
id int primary key,
name varchar(20),
price float
);
# 查看當(dāng)前表中的數(shù)據(jù)
select * from t_product;
# 創(chuàng)建視圖
create view view_selectproduct
as
select id,name from t_product;
# 使用視圖--實(shí)質(zhì)是將語句進(jìn)行了封裝
select * from view_selectproduct;
- 創(chuàng)建各種視圖
(1)封裝實(shí)現(xiàn)查詢常量語句的視圖, 即所謂常量視圖琴昆。
create view view_test1
as
select 3.1415926;
(2)封裝使用聚合函數(shù)(SUM氓鄙、MIN、MAX业舍、COUNT等)查詢語句
create view view_test2
as
select count(name) from t_student;
(3) 封裝實(shí)現(xiàn)排序功能(ORDER BY)查詢語句的視圖
create view view_test3
as
select name from t_product order by id desc;
(4) 封裝實(shí)現(xiàn)表內(nèi)連接查詢語句的視圖
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)封裝實(shí)現(xiàn)表外連接(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)封裝實(shí)現(xiàn)子查詢相關(guān)查詢語句的視圖。
create view view_test6
as
select s.name
from t_student as s
where s.group_id in (
select id from t_group
);
(7)封裝了實(shí)現(xiàn)記錄聯(lián)合(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語句查看視圖名show tables;
(2)SHOW TABLE STATUS語句查看視圖詳細(xì)信息show table status \G;
或show table status from view \G;
或show table status from view like "view_selectproduct" \G;
(3)SHOW CREATE VIEW語句查看視圖定義信息show create view view_selectproduct \G;
(4)DESCRIBE|DESC語句查看視圖設(shè)計(jì)信息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;