建立关系

时间:2011-03-17 05:13:24

标签: sql-server

我创建了以下表并插入了一些值。

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”审阅的所有书籍。我对查询没有任何了解。我怎么写呢?

谢谢,  POOJA

2 个答案:

答案 0 :(得分:1)

SELECT b.bookid as bookid
FROM (books b INNER JOIN bookreview br ON (br.bookid=b.bookid)) 
         INNER JOIN reviewer r ON (br.reviewerid = r.reviewerid)
WHERE year=2003 AND r.reviewername IN ('Sammer Tulpule', 'Hemant Mahta')
GROUP BY b.bookid
HAVING COUNT(r.reviewerid) >= 2

显然,这假设您在bookreview表中没有重复的条目。

答案 1 :(得分:0)

(SELECT b.* FROM books b, bookreview br, reviewer rv WHERE b.year = 2003 AND br.bookid = b.bookid and br.reviewerid = rv.reviewerid and rv.reviewername = 'Sammer Tulpule') 
INTERSECT
(SELECT b.* FROM books b, bookreview br, reviewer rv WHERE b.year = 2003 AND br.bookid = b.bookid and br.reviewerid = rv.reviewerid and rv.reviewername = 'Hemant Mahta')

我正在快速输入,因此可能会出现小错误,但您会得到一般的想法......