2

这是我的表结构

 CREATE TABLE branch_book_list (
   branch_name CHAR(10),
   book_ISBN CHAR (13),
   book_name CHAR(40),
   PRIMARY KEY (branch_name, book_ISBN)
   )

我在表中有这些数据行:

branch_name book_ISBN     book_name                                
----------- ------------- ---------------------------------------- 
Branch A    1-56592-756-7 Transact-SQL Cookbook                   
Branch A    1-56592-401-0 Transact-SQL Programming                
Branch A    1-56592-401-0 Transact-SQL Programming                
Branch B    1-56592-756-7 Transact-SQL Cookbook                   
Branch B    1-56592-756-7 Transact-SQL Cookbook                   
Branch B    1-56592-401-0 Transact-SQL Programming

当我执行此查询时:

SELECT bbl1.*, COUNT(*) DupeCount
FROM branch_book_list bbl1
WHERE bbl1.branch_name = 'Branch A'
GROUP BY bbl1.branch_name, bbl1.book_ISBN, bbl1.book_name
HAVING NOT EXISTS (
      SELECT bbl2.*, COUNT(*)
      FROM branch_book_list bbl2
      WHERE branch_name = 'Branch B'
      GROUP BY bbl2.branch_name, bbl2.book_ISBN, bbl2.book_name
      HAVING bbl1.book_ISBN = bbl2.book_ISBN
         AND bbl1.book_name = bbl2.book_name
         AND COUNT(*) = COUNT(ALL bbl1.book_ISBN))

输出是

branch_name book_ISBN     book_name                                DupeCount   
----------- ------------- ---------------------------------------- ----------- 
Branch A    1-56592-401-0 Transact-SQL Programming                 2
Branch A    1-56592-756-7 Transact-SQL Cookbook                    1

当我只执行查询的顶部时

SELECT bbl1.*, COUNT(*) DupeCount
FROM branch_book_list bbl1
WHERE bbl1.branch_name = 'Branch A'
GROUP BY bbl1.branch_name, bbl1.book_ISBN, bbl1.book_name

我的输出是

branch_name book_ISBN   book_name                   DupeCount
Branch A    1-56592-401-0   Transact-SQL Programming    2
Branch A    1-56592-756-7   Transact-SQL Cookbook       1

但是当完整的查询被执行时,我如何得到这个输出

branch_name book_ISBN     book_name                                DupeCount   
----------- ------------- ---------------------------------------- ----------- 
Branch A    1-56592-401-0 Transact-SQL Programming                 2
Branch A    1-56592-756-7 Transact-SQL Cookbook                    1

谁能告诉我如何获得高于输出?

4

2 回答 2

0

您的 NOT EXISTS 子查询在不同分支中搜索具有相同 ISBN、相同名称和相同数量重复项的行。如果其他分支中的这些条件不匹配,则查询会在输出中包含该行。

现在,两个分支具有相同的项,但重复项的数量不同,这就是返回两个分支 A 项的原因,即它们没有被 HAVING 子句过滤掉。但是尝试例如删除这两项中的一项(Branch B, 1-56592-756-7)您将看到完整查询和简化版本之间的区别。

于 2012-09-22T22:07:16.027 回答
0

你的困惑是什么?过滤器WHERE bbl1.branch_name = 'Branch A' 将所有三个查询限制为仅分支 A 记录...因此,Having Not exists 是多余的...
have 子句检查的任何记录都不能包含 Branch B 数据,因为 Where 子句过滤器的主要部分查询消除了它们。

于 2012-09-22T16:53:46.383 回答