數據庫SQL查詢作業二--水手船

一、創建三張表

①Sailors(sid char(10),sname char(20),rating int,age int),

其中sid是主關鍵字,sid表示水手的編號,sname表示水手的姓名,rating表示水手的級別,age表示水手的年齡。

②Boats(bid char(10),bname char(20),color char(10)),

其中bid表示船的編號是主關鍵字,bname是船的名字,color是船的顏色

③Reserves(sid char(10),bid char(10),rdate date),

Reserves中記錄水手在哪天定了那隻船,其中sid是指向Sailors的外關鍵字,bid是指向Boats的外關鍵字,(sid,bid,rdate)合起來構成Reserves的主關鍵字。

1.查找定了103號船的水手
select s.*, r.bid
from sailors s, reserves r
where s.sid = r.sid and r.bid = '103';

2.查找定了紅色船水手的姓名
select s.sname
from sailors s
where s.sid in (select sid from reserves where bid in (select bid from boats where color = 'red'));

3.查找定了紅色船而沒有定綠色船的水手姓名
select distinct s.sname
from sailors s
where s.sid in (select sid from reserves where bid in (select bid from boats where color = 'red'))
and s.sid not in (select sid from reserves where bid in (select bid from boats where color = 'green'));

4.查找沒有定過船的水手信息
select s.*
from sailors s
where s.sid not in (select sid from reserves);

5.查找定過船而沒有定過紅色船的水手信息
select s.*
from sailors s
where exists (select * from reserves r where s.sid = r.sid)
and not exists (select * from reserves r, boats b where b.bid = r.bid and s.sid = r.sid and b.color = 'red');

6.查找沒有定過紅色船的水手信息
select s.*
from sailors s
where not exists (select * from reserves r where s.sid = r.sid)
and not exists (select * from reserves r, boats b where b.bid = r.bid and s.sid = r.sid and b.color = 'red');

7.查找定過所有船的水手姓名和編號
select s.sname, s.sid
from sailors s
where not exists (select * from boats b where not exists (select * from reserves r where s.sid = r.sid));

8.查找年齡最大的水手姓名和年齡
select s.sname, s.age
from sailors s
where s.age >= all(select age from sailors);

9.統計水手錶中每個級別組的平均年齡和級別組
select s.rating, avg(s.age)
from sailors s
group by s.rating;

10.統計水手錶中每個人數不少於2人的級別組中年滿18歲水手的平均年齡和級別組
select s.rating, avg(s.age)
from sailors s
where s.age > 18
group by s.rating having count(s.rating) >= 2;

11.統計水手錶中每個級別組的人數
select s.rating, count(s.rating)
from sailors s
group by s.rating;

12.統計水手錶中人數最少的級別組及人數
select s.rating, count(s.rating)
from sailors s
group by s.rating
having count(s.rating) <= all(select count(rating) from sailors group by rating);

13.查找定過船而沒有定過相同的船的水手姓名
select s.sname
from sailors
where s.sid in (select sid from reserves)
and s.sid not in (select sid from reserves group by bid having count(bid) >= 2);

14.將年齡小於30的水手級別+1
update sailors
set rating=rating+1
where age < 30;

15.刪除名字叫lubber的水手的定船信息.
delete from reserves where sid = (select sid from sailors where sname = 'lubber'); 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章