Sve*_*sen 3 sql t-sql sql-server sql-server-2008-r2
我很难弄清楚如何提出这个问题,所以我将直接进入示例代码。假设我有这些表:
create table Item
(
ItemId int identity(1,1),
Name nvarchar(256)
)
create table ItemSale
(
ItemSaleId int identity(1,1),
ItemId int,
Price decimal,
CategoryId tinyint
)
Run Code Online (Sandbox Code Playgroud)
我想要检索的是ItemSale不在给定CategoryId. 至少对我来说,复杂的是,如果ItemSale给定的记录存在Item,我不想看到任何记录Item。
所以如果我有这个数据:
insert into Item(Name)
select N'Widget' union all
select N'Foo' union all
select N'Buzz'
insert into ItemSale(ItemId, Price, CategoryId)
select 1, 9.95, 1 union all
select 1, 19.95, 2 union all
select 3, 99.99, 3
Run Code Online (Sandbox Code Playgroud)
而CategoryId我要过滤掉的是 1,那么我不想看到ItemId1(“小部件”)的任何记录。因此,使用该示例数据,我只会看到ID 为 3的ItemSale记录Item。
我知道我的解决方案很可能会涉及某种NOT EXISTSORLEFT JOIN但我正在努力解决如何过滤掉所有记录而不仅仅是符合我的条件的特定记录。我错过了什么?
SQLFiddle:http ://sqlfiddle.com/#!3/79c58
我可能会过度简化您的问题,但我认为这会奏效:
SELECT *
FROM ItemSale i
WHERE NOT EXISTS
( SELECT 1
FROM ItemSale i2
WHERE i.ItemID = i2.ItemID
AND i2.CategoryID = 1
);
Run Code Online (Sandbox Code Playgroud)