member(memb_no, name, age)
book(isbn, title, authors, publishers)
borrowed(memb_no, isbn, date)
图3-21 习题3.21的图书馆数据库
为了解题方便,在数据库中创建这些关系:
create table member (
memb_no varchar,
name varchar,
age int,
primary key (memb_no)
);
create table book(
isbn varchar,
title varchar,
authors varchar,
publishers varchar,
primary key (isbn)
);
create table borrowed (
memb_no varchar,
isbn varchar,
date varchar,
primary key (memb_no, isbn),
foreign key (memb_no) references member on delete no action,
foreign key (isbn) references book on delete no action
);
insert into member values ('会员号_1', '会员_1', 18);
insert into member values ('会员号_2', '会员_2', 19);
insert into member values ('会员号_3', '会员_3', 20);
insert into member values ('会员号_4', '会员_4', 21);
insert into book values ('ISBN_1', '书本_1', '作者_1', '出版商_1');
insert into book values ('ISBN_2', '书本_2', '作者_1', '出版商_1');
insert into book values ('ISBN_3', '书本_3', '作者_1', '出版商_1');
insert into book values ('ISBN_4', '书本_4', '作者_1', '出版商_1');
insert into book values ('ISBN_5', '书本_5', '作者_1', '出版商_1');
insert into book values ('ISBN_6', '书本_6', '作者_1', '出版商_1');
insert into book values ('ISBN_7', '书本_7', '作者_1', '出版商_2');
insert into book values ('ISBN_8', '书本_8', '作者_1', '出版商_2');
insert into book values ('ISBN_9', '书本_9', '作者_1', '出版商_2');
insert into book values ('ISBN_10', '书本_10', '作者_1', '出版商_3');
insert into borrowed values ('会员号_1', 'ISBN_1', '');
insert into borrowed values ('会员号_1', 'ISBN_2', '');
insert into borrowed values ('会员号_2', 'ISBN_3', '');
insert into borrowed values ('会员号_3', 'ISBN_4', '');
insert into borrowed values ('会员号_3', 'ISBN_5', '');
insert into borrowed values ('会员号_3', 'ISBN_6', '');
insert into borrowed values ('会员号_2', 'ISBN_10', '');
select distinct name from member natural join book
natural join borrowed where publishers = '出版商_1';
name
--------
会员_1
会员_2
会员_3
(3 rows)
我们再添加一些数据,让会员_5借阅所有由“出版商_2”出版的书。
insert into member values ('会员号_5', '会员_5', 22);
insert into borrowed values ('会员号_5', 'ISBN_7', '');
insert into borrowed values ('会员号_5', 'ISBN_8', '');
insert into borrowed values ('会员号_5', 'ISBN_9', '');
现在开始实现本题要求的SQL:
with publisher_book(isbn) as (
select isbn from book where publishers = '出版商_2'
)
select distinct name from member
natural join borrowed as B
where not exists (
(select isbn from borrowed where memb_no = B.memb_no)
except
(select isbn from publisher_book)
);
name
--------
会员_5
(1 row)
我们的数据库中的数据没有多于5本借阅的,咱们选择多玩2本的吧。
with borrowed_book(memb_no, name, isbn, publishers) as (
select member.memb_no, name, book.isbn, publishers from
member natural join borrowed natural join book
)
select distinct name from borrowed_book as BB
where exists(
select count(isbn) from borrowed_book
where memb_no = BB.memb_no
group by (memb_no, publishers)
having count(isbn) > 2
)
name
--------
会员_3
会员_5
(2 rows)
select cast(cast(count(isbn) as numeric(18,1))/count(distinct memb_no) as numeric(18,1)) from
borrowed;
numeric
---------
2.5
(1 row)