使用Count进行多个内连接

时间:2014-11-08 10:36:32

标签: sql sql-server count inner-join

我有这样的表格。

Title表:

Book_Title        | ISBN    |Publisher_ID
--------------------------------------
Engineering BK    | 1234556 | 1
Time for a change | 1233333 | 2
Digital Fortress  | 2132312 | 3
Davinci Code      | 2314234 | 3
Angles and Demons | 1232323 | 3

图书ISBN不是普通的ISBN int类型。

Copy表:

   Copy_ID   | ISBN 
-----------------------
      1      | 1234556
      2      | 1233333
      3      | 2132312
      4      | 2314234
      5      | 1232323
      6      | 1232323

Loan表:

Borrower_ID   | Copy_ID | Date_Borrowed |Date_Returned
------------------------------------------------------
     1        |   1     |  2014-10-20   | NULL
     2        |   2     |  2014-10-18   | NULL
     3        |   3     |  2014-10-11   | 2014-10-20
     1        |   4     |  2011-11-11   | 2011-11-25
     2        |   5     |  2010-10-10   | NULL
     4        |   6     |  2012-12-12   | NULL

尚未退回的图书的状态被保存为NULL。

我想选择所有副本借用但仍未返回的所有标题。 换句话说,使用Date_Returned为NULL的贷款表中借用所有副本的标题。

我正试图这样做。

     SELECT DISTINCT(T.Book_Title) AS BookTitle
     FROM Title T
     INNER JOIN Copy CP ON T.ISBN=CP.ISBN
     INNER JOIN Loan LN ON CP.Copy_ID=LN.Copy_ID
     WHERE (SELECT COUNT (CP.Copy_ID) FROM Title T
     INNER JOIN Copy CP ON T.ISBN=CP.ISBN WHERE T.Book_Title=''
    )
    =
    (SELECT COUNT (CP.Copy_ID)FROM Title T INNER JOIN Copy CP ON T.ISBN=CP.ISBN
     INNER JOIN Loan LN ON CP.Copy_ID=LN.Copy_ID
     WHERE LN.Date_Returned IS NULL AND T.Book_Title='')
    GROUP BY T.Book_Title

但在此我不得不在每个子查询中按名称提及书名。但我需要检查标题中的所有标题。

如何解决这个问题?任何帮助都会非常棒。 提前致谢

2 个答案:

答案 0 :(得分:1)

试试这个..

SELECT a.ISBN
FROM   (SELECT ISBN,Count(Copy_ID) cnt
        FROM   Copy
        GROUP  BY ISBN) A
       JOIN (SELECT c.isbn,Count(c.copy_id) cnt
             FROM   copy c
                    JOIN Loan L
                      ON c.copy_id = l.copy_id
             WHERE  l.Date_Returned IS NULL
             Group by c.isbn) b
         ON a.ISBN = B.ISBN
            AND a.cnt = b.cnt
       JOIN title t
         ON t.ISBN = A.ISBN 

答案 1 :(得分:0)

 SELECT T.Book_Title
 FROM Title T
 INNER JOIN Copy CP ON T.ISBN=CP.ISBN
 LEFT JOIN Loan LN ON CP.Copy_ID=LN.Copy_ID
 GROUP BY T.Book_Title
 HAVING sum(case when LN.Copy_ID is null then 1 else 0 end) = 0
 AND sum(case when LN.Date_Returned IS NOT NULL then 1 else 0 end) = 0