NOT EXISTS子查询不能完全加入

时间:2014-04-14 22:53:55

标签: sql sql-server sql-server-2008 tsql exists

我已经阅读过MSDN / Technet,并了解应该有一个来自外部选择的列在子选择内部加入,但是我的表结构并不完全是我所追求的。我有一个包含2列的表格,例如NameType。可能存在Name的重复条目和Type的重复条目,但不是NameType的重复记录(在这两列中看起来像一个唯一的密钥) )。

示例小提琴:http://sqlfiddle.com/#!3/95f3b/3

示例代码:

DECLARE @food AS TABLE (FoodName NVARCHAR(200), FoodType NVARCHAR(200))
DECLARE @NEWfoods AS TABLE (FoodName NVARCHAR(200), FoodType NVARCHAR(200))

INSERT INTO @food (FoodName, FoodType) VALUES 
 ('Apples', 'Fruit')
,('Avocado','Fruit')
,('Bananas', 'Fruit')
,('Mangos', 'Fruit')
,('Bread', 'Grain')
,('Cottage Cheese', 'Dairy')
,('Tacos', 'Meals')
,('Carrots', 'Vegetables')
,('Celery', 'Vegatables')

INSERT INTO @NEWfoods ( FoodName, FoodType ) VALUES  
 ('Avocado','Vegetables')
,('Apples','Fruit')
,('Salt','Preservative')
,('Turkey','Protein')
,('Bread','Grain')
,('Bread','Grain')
,('Tacos','Meals')


SELECT
     f.FoodName
    ,f.FoodType 
FROM @food AS f
WHERE NOT EXISTS (
    SELECT * FROM @NEWfoods
    )

我期望发生的事情是Avocado:Vegetables将被插入,因为基表包含Avocado:Fruit但不包含Avocado:Vegetables(请记住我使用两个列作为唯一键),Bread:GrainTacos:Meals根本不会插入,因为它们已存在于基表中,并且Salt:Preservative也将被插入。

所以在所有这一切结束时,似乎我没有在这里使用正确的功能 - NOT EXISTS本身并不是正确的方法。编码器块!任何帮助,将不胜感激。 :)

2 个答案:

答案 0 :(得分:3)

试试这个。

   SELECT
         f.FoodName
        ,f.FoodType 
    FROM @food AS f
    WHERE NOT EXISTS (
        SELECT * FROM @NEWfoods
        where FoodName = f.FoodName
        AND FoodType = f.FoodType
        )

答案 1 :(得分:1)

DECLARE @food AS TABLE (FoodName NVARCHAR(200), FoodType NVARCHAR(200))
DECLARE @NEWfoods AS TABLE (FoodName NVARCHAR(200), FoodType NVARCHAR(200))

INSERT INTO @food (FoodName, FoodType) VALUES 
 ('Apples', 'Fruit')
,('Avocado','Fruit')
,('Bananas', 'Fruit')
,('Mangos', 'Fruit')
,('Bread', 'Grain')
,('Cottage Cheese', 'Dairy')
,('Tacos', 'Meals')
,('Carrots', 'Vegetables')
,('Celery', 'Vegatables')

INSERT INTO @NEWfoods ( FoodName, FoodType ) VALUES  
 ('Avocado','Vegetables')
,('Apples','Fruit')
,('Salt','Preservative')
,('Turkey','Protein')
,('Bread','Grain')
,('Bread','Grain')
,('Tacos','Meals')


SELECT
     f.FoodName
    ,f.FoodType 
FROM @food AS f
WHERE f.FoodType  NOT IN (
    SELECT N.FoodType FROM @NEWfoods N
    WHERE f.FoodName = n.FoodName AND F.FoodType = n.FoodType
    )
   **--- EITHER THS WAY** 
    select DISTINCT FF.FoodName,FF.FoodType from 
    (select f.FoodName,f.FoodType from @food f
     )AS FF LEFT JOIN @NEWfoods N ON N.FoodName = FF.FoodName AND N.FoodType = FF.FoodType