我有一张城市表,基于邮政编码的州。因此,如果有人搜索芝加哥,由于邮政编码的数量,他们会得到30个芝加哥列表。我想只获得芝加哥的一个列表...但我也想返回zip字段(因为我不需要它)。下面将返回单排“芝加哥,il”,但它也不会通过拉链......它怎么能通过拉链。
SELECT DISTINCT City, State FROM Zips where City like 'chicago' ORDER BY State
拉链表
*Zip | City | State | Lat | Long
答案 0 :(得分:3)
SELECT City, State, MIN(Zip) AS ZIP
FROM Zips
WHERE City = 'chicago'
GROUP BY City, State
ORDER BY State;
或者,也许更具信息性:
SELECT City, State, MIN(Zip) AS Min_ZIP, MAX(Zip) AS Max_ZIP
FROM Zips
WHERE City = 'chicago'
GROUP BY City, State
ORDER BY State;
是否也可以允许输入搜索采用邮政编码和/或城市?
搜索邮政编码:
SELECT City, State, MIN(Zip) AS Min_ZIP, MAX(Zip) AS Max_ZIP
FROM Zips
WHERE Zip = '01234'
GROUP BY City, State
ORDER BY State;
搜索zip和city:
SELECT City, State, MIN(Zip) AS Min_ZIP, MAX(Zip) AS Max_ZIP
FROM Zips
WHERE City = 'chicago'
AND Zip = '01234'
GROUP BY City, State
ORDER BY State;
搜索zip或城市:
SELECT City, State, MIN(Zip) AS Min_ZIP, MAX(Zip) AS Max_ZIP
FROM Zips
WHERE City = 'chicago'
OR Zip = '01234'
GROUP BY City, State
ORDER BY State;
使用单个查询来搜索zip(除非它为null)或城市(除非为null)更为棘手。它通常最终使用问号占位符等 - 并且不能完全跨DBMS移植(而上述查询都可以移植到任何SQL DBMS)。
SELECT City, State, MIN(Zip) AS Min_ZIP, MAX(Zip) AS Max_ZIP
FROM Zips
WHERE (? IS NOT NULL AND City = ?)
OR (? IS NOT NULL AND Zip = ?)
GROUP BY City, State
ORDER BY State;
在这里,如果它有效,你将提供两次城市参数(前两个问号中的每一个一次)和两次zip参数(最后两个问号中的每一个一次)。这进入了讨论哪种编程语言的领域。一些DBMS允许您使用诸如“:n
”之类的表示法来编写每个参数一次,以识别不同的参数:
SELECT City, State, MIN(Zip) AS Min_ZIP, MAX(Zip) AS Max_ZIP
FROM Zips
WHERE (:1 IS NOT NULL AND City = :1)
OR (:2 IS NOT NULL AND Zip = :2)
GROUP BY City, State
ORDER BY State;
我不知道MySQL在这个领域提供了什么。
答案 1 :(得分:1)
假设Zip代码位于名为Zip
的字段中,您可以尝试:
SELECT City, State, MIN(Zip)
FROM Zips
WHERE City LIKE 'chicago'
GROUP BY City, State
对于您所描述的内容,您将被迫选择MIN或MAX邮政编码。
答案 2 :(得分:0)
如果我知道您不关心您回复的邮政编码,我认为您正在寻找
LIMIT 1
将它放在SQL语句的末尾。
SELECT City, State, Zipcode FROM Zips where City like 'chicago' LIMIT 1;
除非你的城市可能出现在多个州?
答案 3 :(得分:0)
假设Zips在Zip上是唯一的,另一种解决方案是:
Select Zip, City, State, Lat, Long
From Zips
Where Zip = (
Select Min(Z1.Zip)
From Zips As Z1
Where Z1.City = 'chicago'
)
任意选择任何名为“芝加哥”的城市的“最低”邮政编码。但是,如果那就足够了,我会感到惊讶。搜索纯粹基于城市名称的邮政编码永远不会在逻辑上足够。至少,您可能希望按州缩小范围,或显示包含所请求城市的所有国家。
如果您想搜索邮政编码或城市,可以这样做:
Select Zip, City, State, Lat, Long
From Zips
Where Zip = (
Select Min(Z1.Zip)
From Zips As Z1
Where Z1.City = 'chicago'
Or Z1.Zip = '12345'
)