2

我正在尝试显示与William. 此查询获取他的邮政编码并使用他的邮政编码查找任何客户。我需要根据邮政编码找到城市 NAME 中的客户。每个城市名称有几个邮政编码。

表城市

zipCode (PK) cityName, stateCode   

表客户

customerId (PK) customerName, customerAddress, zipCode (FK)

到目前为止我的查询...

SELECT 
    cu2.customerName AS 'Customer Name', 
    ci2.cityName AS 'City Name'
FROM 
    customer as cu
INNER JOIN 
    city as ci ON cu.zipCode = ci.zipCode
INNER JOIN 
    city as ci2 ON ci.cityName = ci2.cityName
INNER JOIN 
    customer as cu2 ON ci2.zipCode = cu2.zipCode
                    AND cu2.customerName <> cu.customerName
WHERE 
    cu2.customerName = 'William'

它没有显示任何结果,因为我认为当他所在的城市有另外两个邮政编码时,它只会检查威廉的邮政编码。他的号码是 91709,cityNAME 还有 91708 和 91710。我需要找到该 cityNAME 内的其他客户。

4

3 回答 3

1

我认为这可以做到。

SELECT
  allCustomer.customerName,
  allCity.cityName
FROM Customer finder
  JOIN City finderCity
   ON finder.zipCode = finderCity.ZipCode
  JOIN City allCity
    ON finderCity.CityName = allCity.CityName
    AND finderCity.StateCode = allCity.StateCode
  JOIN Customer allCustomer
    ON allCity.ZipCode = allCustomer.ZipCode
WHERE finder.customerName = 'William'
  and allCustomer.customerName != 'William'

一些注意事项:

  • 如果customerName 不是唯一的,那么我们需要更好地识别William。
  • 仅在 ON 子句中指定连接条件...不要将过滤条件放在那里。
  • 一个城市(作为一个概念)在 City 表中由多行表示,这会导致混淆。
于 2012-11-25T22:06:09.670 回答
1

此 SQL 将在模拟表上执行此操作(我自己尝试过):

SELECT customer.customerName, city.cityName FROM customer INNER JOIN city on city.zipCode = customer.zipCode WHERE city.cityName = (

SELECT city.cityName FROM city WHERE zipCode = (
SELECT city.zipCode FROM customer
INNER JOIN city ON customer.zipCode = city.zipCode
WHERE customer.customerName = 'William'
)

)
于 2012-11-25T22:13:51.287 回答
0
Select cityName,customerName from customer
Join City on Customer.zipCode = City.ZipCode
Where 
And customer.customerName = 'William'
Group by cityName, customerName
于 2012-11-25T22:01:32.520 回答