SELECT项目类型未由实体提供

时间:2009-06-30 21:38:29

标签: sql select not-exists

所以我有一些数据。有实体。实体具有任意数量的项目。项目可以是一组已定义的类型。实体可以具有给定类型的多个项目。我可以获得实体拥有的项目列表。我想要的是获得实体没有项目的类型列表。

这是我的架构:

entities
id name
1  Bob
2  Alice

item_types
id      name 
1       red
2       yellow
3       green
4       blue
5       orange

items
entity_id item_type_id name
1         1            apple
1         2            banana
1         3            lime
1         3            tree
2         3            money
2         5            traffic cone

我想查询Bob的id(1)并获取此列表:

4   blue
5   orange

查询Alice的id(2)并获取:

1   red
2   yellow
4   blue

这可能是我的开始。我会继续努力,但我打赌你偷看我打它。谢谢你的时间。

4 个答案:

答案 0 :(得分:3)

select id, name
from item_types
where id not in
    (select i.item_type_id
    from items i
    inner join entities e
        on e.id = t.entity_id
    where e.Name = 'Bob')

或(有时更快,但优化器一直在变好):

select disctinct t.id, t.name
from item_types t
left outer join items i
    on i.item_type_id = t.id
left outer join entities e
    on e.id = i.entity_id
    and e.Name = 'Bob'
where e.id is null

答案 1 :(得分:0)

鲍勃的

SELECT
  t.id, t.name
FROM
  items i
INNER JOIN
  entities e ON e.id = i.entity_id
INNER JOIN
  item_types t ON t.id = i.item_type_id
WHERE
  e.id <> 1

对于Alice来说,只需交换e.id&lt;&gt; 1到e.id&lt;&gt; 2

答案 2 :(得分:0)

我认为这就是你要找的东西:

SELECT id, name
FROM item_types
WHERE id NOT IN
(
    SELECT DISTINCT item_type_id
    FROM items
    WHERE entity_id = 1
)

“entity_id = 1”代表Bob,根据需要进行更改。

答案 3 :(得分:0)

我会重做这个以使其更好,但这是一个有效的解决方案

set nocount on
go
drop table #entities
drop table #itemtype
drop table #items
create table #Entities
(
EntityId int,
EntityName  varchar (250)
)
create table #ItemType
(
ItemTypeId int,
ItemTypeName    varchar (250)
)

create table #Items
(
EntityId int,
ItemTypeId int,
ItemName    varchar (250)
)
go
insert into #entities values (1, 'Bob')
insert into #entities values (2, 'Alice')
go
insert into #ItemType values (1, 'red')
insert into #ItemType values (2, 'yellow')
insert into #ItemType values (3, 'green')
insert into #ItemType values (4, 'blue')
insert into #ItemType values (5, 'orange')
go
insert into #Items values (1, 1, 'apple')
insert into #Items values (1, 2, 'banana')
insert into #Items values (1, 3, 'lime')
insert into #Items values (1, 3, 'tree')
insert into #Items values (2, 3, 'money')
insert into #Items values (2, 5, 'traffic cone')
go


;WITH ENTITY AS (
SELECT #Entities.EntityId, EntityName, ItemTypeId, ItemName
FROM #Entities, #Items
WHERE #Entities.EntityId = #Items.EntityId
AND #Entities.EntityName = 'Bob'
) 
SELECT #ItemType.* FROM ENTITY
RIGHT JOIN #ItemType ON ENTITY.ItemTypeId = #ItemType.ItemTypeId
WHERE EntityId is NULL


;WITH ENTITY AS (
SELECT #Entities.EntityId, EntityName, ItemTypeId, ItemName
FROM #Entities, #Items
WHERE #Entities.EntityId = #Items.EntityId
AND #Entities.EntityName = 'Alice'
) 
SELECT #ItemType.* FROM ENTITY
RIGHT JOIN #ItemType ON ENTITY.ItemTypeId = #ItemType.ItemTypeId
WHERE EntityId is NULL