數據庫實驗三 Sql多表查詢和視圖
- 一、Sql表
- 二、在線練習
一、Sql表
www.db-book.com
二、在線練習
對所有表執行查詢語句,查看有哪些數據。
select * from tableName;
一、執行以下查詢語句,寫出查詢意圖。
(1) select * from student,takes
where student.ID = takes.ID
根據學號連接stduent表和takes表進行查詢
(2) select * from student natural join takes
stduent表和takes表進行自然連接后進行查詢
(3) select * from student natural left outer join takes
stduent表自然左接takes表后進行查詢
(4) select ID
from student natural left outer join takes
where course_id is null
stduent表自然左接takes表后查詢課程id為空的學生id
(5)select name,instructor.dept_name,building
from instructor,department
where instructor.dept_name = department.dept_name
將instructor表和department表中instructor.dept_name和department.dept_name進行等值連接,然后查詢表中name,instructor.dept_name,building等信息
(6)select name,course_id
from instructor,teaches
where instructor.ID=teaches.ID
將instructor表和teaches表中instructor.ID和teaches.ID進行等值連接,然后查詢表中name,course_id等信息
(7)create view faculty as
select ID,name,dept_name
from instructor
創建一個包含instructor中select ID,name,dept_name數據的視圖
(8)select * from faculty
查詢faculty視圖
(9)create view phy_fall_2017 as
select course.course_id,sec_id,building,room_number
from course,section
where course.course_id = section.course_id
and course.dept_name = ‘Physics’
and section.semester =‘Fall’
and section.year = ‘2017’
創建一個列出Physics系在2017年秋季學期所開設的所有課程段,以及每個課程段在那棟建筑的那個房間授課的信息的視圖
(10) select * from phy_fall_2017
查詢from phy_fall_2017視圖
(11) drop view phy_fall_2017
刪除phy_fall_2017視圖
(12)
create view dept_total_salary(dept_name,total_salary)
as
select dept_name,sum(salary)
from instructor
group by dept_name
創建一個dept_total_salary視圖,并且以dept_name,total_salary作為表頭,其中的數據從instructor的dept_name,sum(salary)獲取,并且按dept_name分組
(13) select * from dept_total_salary
查詢dept_total_salary視圖
二、寫出SQL查詢語句
(14)找出名叫Einstein的教師所教授的所有學生的學號,保證結果中沒有重復。
select ID
from student
where student.ID in (select s_ID
from advisor join instructor
on i_ID in(
select ID
from instructor
where name=‘Einstein’));
(15)找出2017年秋季開設的每個課程的選課人數。
select course_id, sec_id, count(ID)
from section natural join takes
where semester = ‘Fall’ and year = 2017
group by course_id, sec_id
(16)從2017年秋季開設的所有課程段中,找出最多的選課人數。
select Max(cnt)
from (
select Count(ID) as cnt
from section natural join takes
where semester = ‘Fall’ and year = 2017 group by course_id, sec_id
)
(17)找出2017年秋季選課人數最多的課程編號。
with Fall_2017 as
(
select course_id, sec_id, count(ID) as cnt
from section natural join takes
where semester = ‘Fall’ and year = 2017
group by course_id, sec_id
)
select course_id,sec_id
from Fall_2017
where cnt = (select max(cnt) from Fall_2017)