仅当tbl2中的字段不匹配时才在tbl1中选择

时间:2013-07-19 17:42:30

标签: sql ms-access ms-access-2007

如果在表“b”中的两个字段中找不到匹配项,我试图仅选择表“a”中的记录。我想出了以下内容,但它只是返回所有记录。代码看起来很简单,Access没有正确处理SELECT 1功能还是我没有正确使用它?感谢您的帮助。

SELECT a.[Part Number], 
       a.[Company Name], 
       a.[Customer Name], 
       a.[Customer Number], 
       a.[Salesperson Initials], 
       a.[Date Received], 
       a.Quantity, 
       a.ExtCost, 
       a.ExtPrice, 
       a.[Gross Margin]
FROM   [1: Orders in the period] As a
WHERE EXISTS (SELECT 1 
              FROM [Price Adjustments New Gross Margin] As b 
              WHERE b.[Part Number]<>a.[Part Number] AND b.[Customer Name]<>a.[Customer Name]);

1 个答案:

答案 0 :(得分:1)

LEFT JOIN ab并仅返回bIs Null的行。

SELECT a.[Part Number], 
       a.[Company Name], 
       a.[Customer Name], 
       a.[Customer Number], 
       a.[Salesperson Initials], 
       a.[Date Received], 
       a.Quantity, 
       a.ExtCost, 
       a.ExtPrice, 
       a.[Gross Margin]
FROM
    [1: Orders in the period] AS a
    LEFT JOIN [Price Adjustments New Gross Margin] AS b 
    ON
            a.[Part Number]=b.[Part Number]
        AND a.[Customer Name]=b.[Customer Name]
WHERE b.[Part Number] Is Null;

如果你更愿意坚持EXISTS,我认为这可能会得到你想要的。

WHERE NOT EXISTS
    (
        SELECT 1 
        FROM [Price Adjustments New Gross Margin] AS b 
        WHERE
                b.[Part Number]=a.[Part Number]
            AND b.[Customer Name]=a.[Customer Name]
    );