1

我正在使用 sql server 2008 R2 并且我有表:

Book: id, name, ...  >> 3500 rows
BookChapter: id, bookid, content(nvarchar(max)... >> it has about 300000 rows

2之间没有关系。

现在我想计算所有目前没有章节的书。

SELECT     COUNT(Id) AS Expr1
FROM         dbo.Book
WHERE     (Id NOT IN  (SELECT BookId FROM dbo.BookChapter))   

总是给超时过期。我怎样才能实现它?

4

3 回答 3

4

尝试使用与不存在类似但有时性能更好的左连接。

select count(1) as Counts
from 
    dbo.Book B
    left join dbo.BookChapter BC on BC.BookID = B.ID
where
    BC.BookID is null
于 2013-07-12T03:08:04.420 回答
0

您的子查询变得非常大。您可以尝试按 BookId 对其进行分组。

SELECT COUNT(Id) AS Expr1
FROM   dbo.Book
WHERE  (Id NOT IN  (SELECT BookId FROM dbo.BookChapter GROUP BY BookId)) 

另一个选项使用NOT EXISTS;

SELECT COUNT(B.Id) AS count
FROM   dbo.Book B
WHERE  NOT EXISTS (SELECT * FROM dbo.BookChapter WHERE BookId=B.BookId))
于 2013-07-12T02:59:27.010 回答
0

不要使用“不在”。它太慢了。您可以按照 Apartidge 的第二个建议使用“不存在”,或者您可以做一些完全不直观的事情,如下所示:

select count(*) BooksWithoutChapters
from book
where id in 
(select id
from book
minus 
select bookid
from BookChapter
)
于 2013-07-12T03:05:08.257 回答