2

我正在尝试显示与William. 在我的customer表格中,我将邮政编码作为zipCode列。在我的city表中,我的城市名称为cityName.

表城市

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

2 回答 2

0

我会将您的架构视为:

客户(客户 ID、客户名称、城市 ID、...)

城市 (cityid, cityName, zip, ...)

要检索与“威廉”居住在同一城市的客户,您需要

SELECT cust.customerName, cit.city_name
FROM customer cust
JOIN city cit ON cust.cityid = cit.cityid
WHERE cit.cityid IN (
     SELECT cit2.cityid
     FROM city cit2
     JOIN customer cust2 ON cit2.cityid = cust2.cityid
     WHERE cust2.customerName = 'William'
)
于 2012-11-25T04:49:30.517 回答
0
SELECT ct.customerName
FROM city c JOIN customer ct ON c.ZipCode = ct.ZipCode
WHERE c.CityName IN (
                     SELECT c.CityName
                     FROM customer ct JOIN city c ON ct.ZipCode = c.ZipCode 
                     WHERE ct.CustomerName = 'William'
                     )
于 2012-11-25T10:55:26.360 回答