0

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

大学表 - UniversityName、UniversityId

BookLease 表 - BookId、UniversityId、LeaseDate

图书表 - BookId、UniversityId、类别、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"

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

4

2 回答 2

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]
于 2012-10-26T09:10:09.353 回答
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"
于 2012-10-26T09:14:33.577 回答