如何根据不共享字段的 table 过滤查询?

How to filter query based on table where they dont share a field?

好的,所以我一直在研究这个 SQL 语句,但就是想不通。我需要能够看到 2017 年客户借用的前 5 名作者。我的 table 看起来像这样

1. Client - fields (clientId,clientFirstName,clientlastName,clidentDoB)
2.author - fields (AuthorID, AuthorFirstname, AuthorLastname,AuthorNation )
3. book - fields (BookId, BookAuthor,BookTitle,BookGenre)
4. borrower - fields (borrowID,BorrowDate, ClientID,BookId)

所以我知道我需要从作者 table 那里提取名字,根据借书的数量,我也明白 borrower.bookId 等于 book.BookId 和 Author.AuthorID 等于 Book.BookAuthor。 我应该能够设置它,以便它看到 2017 年借来的书,然后通过获取 borrowBookId 并将相同 Id 的每个实例加在一起并查看 bookID 与 BookAuthor 匹配的书 table 然后使用它来比较 ID 以打印名字和姓氏。

我试过了

SELECT author.authorfirstname,author.authorlastname 
FROM author Join ON author.authorid = book.bookauthor   
WHERE (borrower.borrowdate <='31/12/2017' AND borrower.borrowdate >= '01/01/2017'); 

我知道这行不通,但我不确定如何建立从作者到借款人的桥梁。

示例数据及其预期输出。

确定。假设我有 4 位作者,我们想要前 3 位。我们也只有 2017 年的借贷。客户端 table 并不是真正需要的,所以让我们用一些数据填充其他的。 table 与原始问题示例中相同的字段名称为
作者 table

(1,bob,ross, USA) 
(2, fred, martin, USA) 
(3, alex,joe,CAN)
(4, dan, reed, can)                          

图书table

(1,1,bobsbook,fantasy) 
(2,1,bobagain,fantasy) 
(3,1,returnofbob,fantasy)
 (4,2,fredsadventure,fantasy) 
(5, 2, fedagain, fantasy) 
(6, 2, fedstrikes, fantasy) 
(7,3,alexjoes, fantasy)
 (8, 3, alexjoeagain,fantasy)
(9,4, dansbook, fantasy)

借table

(1, 20/01/2017,,1, 1)
(2, 20/01/2017,,3, 2)
(3, 20/01/2017,,2, 1)
(4, 20/01/2017,,1, 3)
(5, 20/01/2017,,6, 2)
(6, 20/01/2017,,8, 4)
(7, 20/01/2017,,4, 4)
(8, 20/01/2017,,9, 6)
(9, 20/01/2017,,2, 7)
(10, 20/01/2017,,3, 9)
(11, 20/01/2017,,4, 9)

最终结果会是

AuthorFirstName  AuthorLastname 
bob               ross
Fred              Martin
Dan               Reed 

这是因为他们在 2017 年的日期范围内借用最多,顺序为 bob 在 5,fred 在 3,dan 在 2。它也只打印前 3 个人,所以 alex joe 被排除在外列表。

@fahmi 给出的代码

SELECT author.authorfirstname,author.authorlastname 
FROM author 
Join book ON author.authorid = book.bookauthor
join borrower on book.bookid=borrower.bookid
WHERE borrower.borrowdate <='31/12/2017' AND borrower.borrowdate >= '01/01/2017'

;

这给了我一个作者列表,它列出了 burrow 的每个实例,但我需要合并列表,所以我只看到一个名字,这样它就可以按大多数借用顺序排序并自我限制。

您需要另一个与 book.bookid=borrower.bookid 关系

的借款人的连接
SELECT top 3 author.authorfirstname,author.authorlastname,count(borrower.bookid) as cnt
FROM author 
Join book ON author.authorid = book.bookauthor
join borrower on book.bookid=borrower.bookid
WHERE borrower.borrowdate <='31/12/2017' AND borrower.borrowdate >= '01/01/2017'
group by author.authorfirstname,author.authorlastname
order by cnt desc

使用 Oracle 的 TOP-N 查询功能,

select au.authorfirstname
      ,au.authorlastname 
  from author au
  join book bk
    on au.authorid = bk.bookauthor
  join borrower bw
    on bk.bookid=bw.bookid
 where extract(year from bw.borrowdate) 
       = 2017
group by au.authorfirstname
        ,au.authorlastname
order by count(bk.bookid) desc
fetch first 3 rows with ties;