DB2中的复杂SQL问题

时间:2016-09-22 09:13:06

标签: sql db2

我有一个表TABLE_CLIENT_BOOK,其中包含USER_IDBOOK_CODE。此表显示所有书籍都具有特定的USER_ID。

USER_ID         BOOK_CODE
------------------------------
1               123
1               124
1               567
2               123
2               432
3               432
3               567
-------------------------------

我有另一张表TABLE_BOOK,其中包含有关每本书的详细信息。

BOOK_CODE        DETAILS
----------------------------------
123              abcd
124              pqrs 
432              xyzw
567              lmnop
568              efgh
----------------------------------

我想在两个表之间编写一个查询,它会吐出USER_IDBOOK_CODE,其中BOOK_CODE列应该具有来自TABLE_BOOK的所有书籍的ID,该用户不会有。对于例如用户1没有书籍432和568,用户2没有书籍,567和568,用户3没有书籍124,124,568。

所以查询的结果表是:

USER_ID     BOOK_CODE
----------------------------
1           432
1           568
2           124
2           567
2           568
3           123
3           124
3           568
-----------------------------

此报告用于宣传用户没有的图书。

如何在DB2 9中的SQL中实现这一点?

感谢阅读!

1 个答案:

答案 0 :(得分:3)

执行CROSS JOIN以获取所有用户/书籍组合。使用NOT EXISTS排除现有的组合:

select distinct tcb.USER_ID, tb.BOOK_CODE
from TABLE_CLIENT_BOOK tcb
    cross join TABLE_BOOK tb
where not exists (select * from TABLE_CLIENT_BOOK tcb2
                  where tcb2.USER_ID = tcb.USER_ID
                    and tcb2.BOOK_CODE = tb.BOOK_CODE)
order by tcb.USER_ID, tb.BOOK_CODE

或者,EXCEPT

select tcb.USER_ID, tb.BOOK_CODE
from TABLE_CLIENT_BOOK tcb
    cross join TABLE_BOOK tb
EXCEPT
select USER_ID, BOOK_CODE
from TABLE_CLIENT_BOOK
order by tcb.USER_ID, tb.BOOK_CODE

此处不需要DISTINCTEXCEPT删除重复项。

执行为:

SQL>select distinct tcb.USER_ID, tb.BOOK_CODE
SQL&from TABLE_CLIENT_BOOK tcb
SQL&    cross join TABLE_BOOK tb
SQL&where not exists (select * from TABLE_CLIENT_BOOK tcb2
SQL&                  where tcb2.USER_ID = tcb.USER_ID
SQL&                    and tcb2.BOOK_CODE = tb.BOOK_CODE)
SQL&order by tcb.USER_ID, tb.BOOK_CODE;
    USER_ID   BOOK_CODE
=========== ===========
          1         432
          1         568
          2         124
          2         567
          2         568
          3         123
          3         124
          3         568

                  8 rows found

SQL>select tcb.USER_ID, tb.BOOK_CODE
SQL&from TABLE_CLIENT_BOOK tcb
SQL&    cross join TABLE_BOOK tb
SQL&EXCEPT
SQL&select USER_ID, BOOK_CODE
SQL&from TABLE_CLIENT_BOOK
SQL&order by tcb.USER_ID, tb.BOOK_CODE;
    USER_ID   BOOK_CODE
=========== ===========
          1         432
          1         568
          2         124
          2         567
          2         568
          3         123
          3         124
          3         568

                  8 rows found