我正在尝试展示与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中的其他客户。
答案 0 :(得分: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'
一些注意事项:
答案 1 :(得分: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'
)
)
答案 2 :(得分:0)
Select cityName,customerName from customer
Join City on Customer.zipCode = City.ZipCode
Where
And customer.customerName = 'William'
Group by cityName, customerName