数据库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'); 

猜你喜欢

转载自blog.csdn.net/WxqHUT/article/details/105277993