0

我正在尝试列出与任何员工不在同一州(或地区)的所有美国客户公司名称。它应该返回 10 行。我为此使用了以下查询

SELECT Customers.CompanyName
FROM Customers
WHERE Customers.Country='USA'
  AND Customers.Region IN
    (SELECT Customers.Region
     FROM Customers
     GROUP BY Customers.Region HAVING COUNT(Customers.Region)=1);

但它只返回 6。

数据库是北风。**公司名


here is the output
Old World Delicatessen
Let's Stop N Shop
Save-a-lot Markets
The Cracker Box
Rattlesnake Canyon Grocery
Split Rail Beer & Ale**
4

2 回答 2

4

试试这个

SELECT CompanyName
  FROM Customers
 WHERE Country='USA' AND 
       Region NOT IN
           (SELECT DISTINCT Region
              FROM Employees 
             WHERE Region IS NOT NULL);

输出

CompanyName
----------------------------------------
Great Lakes Food Market
Hungry Coyote Import Store
Let's Stop N Shop
Lonesome Pine Restaurant
Old World Delicatessen
Rattlesnake Canyon Grocery
Save-a-lot Markets
Split Rail Beer & Ale
The Big Cheese
The Cracker Box

(10 row(s) affected)

在您的问题中,您说您需要与任何员工不在同一州(或地区)的所有美国客户的公司名称。但是在您的查询中,您试图从客户表中获取区域。

更新:我相信你知道,但以防万一:

显式检查NULL子查询 ( WHERE Region IS NOT NULL) 中的值是至关重要的。没有它,查询将成功运行,但不会返回任何行。

SELECT CompanyName
  FROM Customers
 WHERE Country='USA' AND 
       Region NOT IN
           (SELECT DISTINCT Region
              FROM Employees);

输出:

CompanyName
----------------------------------------

(0 row(s) affected)

我想您尝试完成的练习是为了确保您了解子查询中的 NULL。

于 2013-03-03T22:04:56.717 回答
1

您的查询根本不检查Employees表!看看:

SELECT Customers.CompanyName, customers.Region
FROM Customers
WHERE Customers.Country='USA'
AND NOT EXISTS(SELECT 1 FROM Employees WHERE Employees.Region = Customers.Region)

或者

SELECT Customers.CompanyName, customers.Region
FROM Customers
WHERE Customers.Country='USA'
AND  Customers.Region NOT IN (SELECT DISTINCT Employees.Region FROM Employees WHERE Employees.Region IS NOT NULL)

两个查询都返回:

Great Lakes Food Market         OR
Hungry Coyote Import Store      OR
Let's Stop N Shop               CA
Lonesome Pine Restaurant        OR
Old World Delicatessen          AK
Rattlesnake Canyon Grocery      NM
Save-a-lot Markets              ID
Split Rail Beer & Ale           WY
The Big Cheese                  OR
The Cracker Box                 MT
于 2013-03-03T22:06:23.433 回答