2012-10-26 75 views
0

表結構(這是效率不高,但我有它的工作,我不能改變它。):SQL - 三個表加入

大學表 - UniversityName,UniversityId

BookLease表 - BookId,UniversityId,LeaseDate

Book Table - BookId,UniversityId,Category,Page_Count。

我已經找到了大學這個名字是「XYZ」的閱讀/租借的總頁數。這是我迄今爲止:

select sum(bookTable.Page_count) 
from University u 
join (select bl.UniversityId AS universityId, b.page_count as Counter 
     BookLease bl 
     join Book bk 
      on bl.BookId = bk.BookId) as bookTable 
on 
    bookTable.universityId = u.UniversityId 
where 
    u.Name = "XYZ" 

這似乎是錯誤的,效率低下。是嗎?有沒有更好的方法來寫這個?

+0

哪個SQL?也提供版本。 – yogi

+0

您的sql中存在錯誤。 b不是有效的表別名。 Book或BookLease中是page_count? – Codeguy007

+0

@ Codeguy007:「Book Table - BookId,UniversityId,Category,Page_Count。」 – Guffa

回答

0

你可以這樣做:

select 
    sum(b.page_count) as pages_read 
    , count(bl.bookid) as no_leased 
from university u 
    inner join book b on b.universityid = u.universityid 
    inner join booklease bl on bl.bookid = b.bookid 
          and bl.universityid = u.universityid 
where u.name = 'XYZ' 
and bl.lease_date > [some lease date] 
+0

總租用:select book(bl)內部加入大學在bl.universityid = u.universityid其中u.universityName ='xyz' – Larry

+0

-1如果您沒有加入'Book'表上' BookLease'表,那麼您只能獲得可用書籍中的頁數,而不是讀取/租用的頁數。 – Guffa

+0

@拉里 - 謝謝!在回答中更正。 – davek

0

在桌子上就直接加入,而不是一個子查詢:

select 
    sum(bk.Page_count) 
from 
    University u 
    inner join BookLease bl on bl.UniversityId = u.UniversityId 
    inner join Book bk on bk.BookId = bl.BookId 
where 
    u.Name = "XYZ"