sql - 三个表连接

时间:2012-10-26 09:07:25

标签: sql

表结构(效率不高,但我必须使用它,我无法更改它。):

大学表 - UniversityName,UniversityId

BookLease Table - BookId,UniversityId,LeaseDate

书籍表 - 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"

这似乎是错误和低效的。是吗?有没有更好的方法来写这个?

2 个答案:

答案 0 :(得分: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]

答案 1 :(得分: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"
相关问题