我创建了以下表并插入了一些值。
create table books
(bookid integer primary key,
booktitle varchar(20),
year integer,
publisherid integer foreign key references publisher(publisherid),
price integer,
number integer)
create table publisher
(publisherid integer primary key,
publishername varchar(20))
create table author
(authorid integer primary key,
authorname varchar(20))
create table bookauthor
(bookid integer foreign key references books(bookid),
authorid integer references author(authorid),
earnings integer)
create table bookreference
(bookid integer foreign key references books(bookid),
referencebook varchar(20),
times integer)
create table reviewer
(reviewerid integer primary key,
reviewername varchar(20))
create table bookreview
(bookid integer foreign key references books(bookid),
reviewerid integer foreign key references reviewer(reviewerid),
score integer)
现在,我想在SQL Server 2000中解决以下查询。
查找2003年出版并由'Sammer Tulpule'和'Hemant Mahta'评论的所有书籍
所以,我运行了以下查询。
SELECT B.booktitle
FROM bookreview BR
INNER JOIN books B ON BR.bookid = B.bookid
INNER JOIN reviewer R ON R.reviewerid = BR.reviewerid
WHERE
B.year=2003
AND R.reviewername IN('Sammer Tulphule','Hemant Mahta')
但是,由此我得到了2003年出版并由评审员评论过的所有书籍的名称。实际上,我想要在2003年出版的所有书籍的名称,并且两者都不是其中之一。
那么,我该如何修改该查询呢?
谢谢&问候, POOJA。
答案 0 :(得分:1)
您需要两次加入bookreview和bookreviewer表(每个必需的审阅者一次)。您可以使用不同的表别名来实现此目的:
select B.booktitle
from books B
join bookreview BR1 on B.bookid = BR1.bookid
join reviewer R1 on R1.reviewerid = BR1.reviewerid
join bookreview BR2 on B.bookid = BR2.bookid
join reviewer R2 on R2.reviewerid = BR2.reviewerid
where B.year = 2003 and
R1.reviewername = 'Sammer Tulphule' and
R2.reviewername = 'Hemant Mahta'
您也可以使用exists子句执行此操作:
select B.booktitle
from books B
where
B.year = 2003 and
exists (select 1
from bookreview BR
join reviewer R on BR.reviewerid = R.reviewerid
where BR.bookid = B.bookid and
R.reviewername = 'Sammer Tulphule') and
exists (select 1
from bookreview BR
join reviewer R on BR.reviewerid = R.reviewerid
where BR.bookid = B.bookid and
R.reviewername = 'Hemant Mahta')
这可能更容易理解。
答案 1 :(得分:1)
稍微扩展您的查询。此查询比使用自联接或存在(相关子查询)更快 - 它只通过表一次。
SELECT B.booktitle
FROM bookreview BR
INNER JOIN books B ON BR.bookid = B.bookid
INNER JOIN reviewer R ON R.reviewerid = BR.reviewerid
WHERE
B.year=2003
AND R.reviewername IN('Sammer Tulphule','Hemant Mahta')
GROUP BY B.booktitle
HAVING COUNT(distinct R.reviewername) = 2