坚持SQL查询(区别?)

时间:2012-11-09 19:25:40

标签: sql ms-access

我正在为图书馆制作一个网页,我需要制作一个列表,显示过去一年内没有租借的所有图书。

目前我有一个在Rent表上过滤的查询,其中所有记录都是租借的书籍。但可以多次租用,以便一本书可以在表格中多次出现。问题是,当一本书没有租给一个人超过一年,但同一本书在过去一年内租给另一个人时,它仍然显示该书,因为它看到一本记录满足条件。但我需要知道去年哪本书根本没有租来。任何人都可以帮我吗?

我将实际查询更改为更易于理解的查询(语言差异),因此请勿检查错误的拼写或简单的语法问题。

我的查询a.t.m。:

SELECT
  Book.BookID,
  Book.BoekTitle, 
  Writer.WriterName 
FROM (
    (Book INNER JOIN BookWriter ON Book.BookID=BookWriter.BookID) 
    INNER JOIN Writer ON BookWriter.WriterID=Writer.WriterID
  )
  INNER JOIN BookRenting ON Book.BookID=BookRenting.BookID
WHERE
  BookRenting.RentDate < DATEADD('yyyy', -1, NOW());

我使用MS Access数据库!

先谢谢你的帮助!

3 个答案:

答案 0 :(得分:0)

我认为这可以归结为以更好的方式构建查询。

尝试使用NOT IN <subquery>而不是加入。这使您的查询更加模块化,更易于理解:

SELECT Book.*, Writer.*
FROM
Book 
INNER JOIN BookWriter ON Book.BookID=BookWriter.BookID
INNER JOIN Writer ON BookWriter.WriterID=Writer.WriterID
WHERE
Book.BookID NOT IN (
    SELECT BookRenting.BookID
    FROM BookRenting 
    WHERE BookRenting.RentDate >= DATEADD('yyyy', -1, NOW())
); 

我没有Access,所以我没有测试过这个

答案 1 :(得分:0)

首先,您可能需要处理该书从未租用的情况。这需要外部联接。

这可以让你得到你想要的东西:

select b.BookID, b.BookTitle, w.WriterName
from book b left outer join
     (select BookId, max(RentDate) as MaxRentDate
      from BookRenting br
      group by BookId
     ) br
     on b.BookId = br.BookId left outer join
     BookWriter bw
     on b.BookId = bw.BookId left outer join
     Writer w
     on bw.WriterId = w.WriterId
where br.MaxRentDate < DATEADD('yyyy', -1, NOW());

并且,我想补充一点,书籍可以有多个作家。您仍然会在输出中获得重复项。

答案 2 :(得分:-1)

您似乎缺少<sometablehere> INNER JOIN Writer ON BookWriter.WriterID=Writer.WriterID

所以它可能看起来像:

SELECT
  Book.BookID,
  Book.BoekTitle, 
  Writer.WriterName 
FROM (
    (Book INNER JOIN BookWriter ON Book.BookID=BookWriter.BookID) 
    **CODETALKSTABLE** INNER JOIN Writer ON BookWriter.WriterID=Writer.WriterID
  )
  INNER JOIN BookRenting ON Book.BookID=BookRenting.BookID
WHERE
  BookRenting.RentDate < DATEADD('yyyy', -1, NOW());