我正在使用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))
总是让超时过期。我怎样才能实现它?
答案 0 :(得分: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
答案 1 :(得分: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))
答案 2 :(得分:0)
不要使用“不在”。这太慢了。根据apartidge的第二个建议你可以使用“not exists”,或者你可以做一些完全不直观的事情:
select count(*) BooksWithoutChapters
from book
where id in
(select id
from book
minus
select bookid
from BookChapter
)