SQL Server 2005如何查找拥有所有书籍的用户

时间:2012-03-21 04:43:37

标签: sql sql-server sql-server-2005

我正在尝试查询具有所有计算机书籍的用户。例如,我有两个表:

1)项目表

|itemid |item_name          |
------------------------------
|1      | computerbook1     |    
|2      | computerbook2     |    
|3      | computerbook3     |
|4      | mathbook1         |    
|5      | mathbook2         |    
|6      | physicsbook       | 

2)userinventory table

|used_id | name_item        |
-----------------------------
|1       | computerbook1    |    
|1       | computerbook2    |    
|1       | computerbook3    |    
|2       | computerbook1    |    
|2       | mathbook1        |    
|2       | physicsbook      |    
|3       | computerbook1    |    
|3       | computerbook3    |

由于用户" 1"有了所有的电脑书,我想做出返回用户1的查询。

我做的是......

Create Table #tmp (
    Classname [varchar](50) NOT NULL
)

INSERT INTO #tmp
SELECT DISTINCT item_name  
  FROM ITEM
 WHERE item_name  like 'computerbook%'

我想比较找到拥有所有项目的用户..

但是,我不确定该怎么做..因为我不能使用计数或任何聚合。

请勿使用" count"

无论如何都知道他们找到拥有所有电脑书的用户ID吗?

3 个答案:

答案 0 :(得分:2)

我的解决方案的关键是except子句。我对所有用户/书籍的可能性进行交叉连接,然后 - 使用except子句 - 获取不满足这些可能性的所有用户的列表。这是A =所有可能性,B =实际数据,A除了B之外只包含缺少A行的用户。从那里,我查询库存表中表示的所有用户,这些用户不在子库中返回的用户-query。我承认它很复杂,可以使用细分到临时表。

SELECT user_id
FROM   userinventory
EXCEPT
(
  SELECT user_id
  FROM  (
        SELECT UX.user_id, II.item_name 
        FROM item II, (SELECT UU.user_id FROM userinventory UU) UX
        WHERE II.item_name LIKE 'computerbook%'
        EXCEPT
        SELECT UU.user_id, UU.name_item
        FROM   userinventory UU
        ) XX
)

答案 1 :(得分:1)

这样的事情:

SELECT DISTINCT userid FROM userinventory WHERE NOT EXISTS (SELECT null
    FROM item WHERE NOT EXISTS (SELECT null FROM userinventory i2
      WHERE i2.name_item = item.item_name AND i2.user_id = userinventory.userid))

换句话说,我们正在寻找拥有至少一个项目的不同用户,这些项目中没有拥有的项目。

答案 2 :(得分:0)

declare @Item table(itemid int, item_name varchar(30))
insert @item values(1, 'computerbook1')
insert @item values(2,'computerbook2')
insert @item values(3,'computerbook3')
insert @item values(4,'mathbook1')
insert @item values(5,'mathbook2')
insert @item values(6,'physicsbook')

declare @userinventory table(user_id int, name_item varchar(30))
insert @userinventory values(1,'computerbook1')
insert @userinventory values(1,'computerbook2')
insert @userinventory values(1,'computerbook3')
insert @userinventory values(2,'computerbook1')
insert @userinventory values(2,'mathbook1')
insert @userinventory values(2,'physicsbook')
insert @userinventory values(3,'computerbook1')
insert @userinventory values(3,'computerbook3')

;with users as
(
  select distinct user_id from @userinventory
), books as
(
  select item_name from @item
  where item_name like 'computerbook%'
), missingbooks as
(
  select * from users cross join books
  except 
  select user_id, name_item from @userinventory
)
select user_id from users
where user_id not in (select user_id from missingbooks)