1、視圖是表?沒錯,但是是一張虛擬表,視圖的字段是由我們自定義的,視圖只供查詢,數據不可更改,查詢數據來源於我們建立的實體表。
2、使用視圖的優勢?視圖可以將多個複雜關聯表,提取出我們需要的信息,優化查詢速度。
3、如何創建視圖?
我們先建立三張表;如下:
這個是典型的一對多和一對一的關係,那麼,假如每張表的數據都在一萬條數據以上,現在查詢在潢高上學的學生姓名?
首先,我們分析一下,在潢高上學?首先是一個高中,那麼我們會有一條Sql where school='潢高',
查詢出一個List,得到gradeids,然後再到grade中根據gradeids查詢這麼多grades對應的studentids,在使用這些studentsid查詢出students循環最後得到name?
是不是很累贅?查詢是不是很影響性能?
觀察得知,這三張表每兩張表之間都是通過id進行關聯的,如果我們通過id將三張表組成一張表,是不是很方便?
我們來關聯學校表和年級表:這個年級ID我們不要,ok?
1
|
select
s.id as
schoolId,s.school as
schoolName,s.gradeid as
gradeid,g.grade as
gradeName,g.studentid as
studentid from school s,grade g
where s.gradeid=g.id; |
那麼我們再關聯上學生表,學生表的id等於年級表的studentid ok?
1
2
|
SELECT
s.id as schoolId,s.school
as schoolName,s.gradeid
as gradeid,g.grade
as gradeName,g.studentid
as studentid ,t.` name `
as studentName,t.age
as studentAge from
school s,grade g,student t where
s.gradeid=g.id and
g.studentid=t.id; |
ok,到了這裏?我們再看運行結果?
那麼我們想查詢在潢高上學的學生姓名,where schoolName='潢高',獲取的list循環得到Object,通過Object.getStudentName,就可以了?
所以需要將查詢到的結果,建立爲一張虛擬表,這樣才能操作,通過這個create view 視圖名 as 命令建立:
意思就是將查詢結果創建爲名稱爲table_sgt的一張虛擬表:
1
|
create
view table_sgt as ( select
s.id as
schoolId,s.school as
schoolName,s.gradeid as
gradeid,g.grade as
gradeName,g.studentid as
studentid ,t.` name `
as studentName,t.age
as studentAge
from school s,grade g,student t
where s.gradeid=g.id
and g.studentid=t.id); |
我們在使用視圖的時候,需要把它看做爲一張表,建立一張實體表需要做的步驟,視圖也都需要(例如,實例化,配置映射文件,對象的屬性get,set方法)
注意視圖所查詢出來的數據只能進行查看,不能增刪改!