SQL子查询:这是如何产生输出的?

时间:2012-09-22 16:47:19

标签: sql

这是我的表结构

 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))

OUTPUT

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

任何人都可以告诉我如何获得以上输出吗?

2 个答案:

答案 0 :(得分:0)

你的困惑是什么?过滤器WHERE bbl1.branch_name = 'Branch A' 将所有三个查询限制为仅分支A记录... 因此,“不存在”是多余的...
 没有被having子句检查的记录可以有Branch B数据,因为查询主要部分中的Where子句过滤器会消除它们。

答案 1 :(得分:0)

您的NOT EXISTS子查询搜索不同分支中具有相同ISBN,相同名称​​和相同重复数的行。如果其他分支中的条件不匹配,则查询包括输出中的行。

现在,两个分支具有相同的项目,但重复的数量不同,这就是为什么返回两个分支A项目,即HAVING子句的they are not filtered out。但试试,例如删除完整查询和简化版之间的两个(Branch B, 1-56592-756-7)项之一和you'll see the difference