我有一个所有美国邮政编码及其对应的州和国会选区的数据库表,如下所示。
id | zipcode | state_abbr | district
1 30080 GA 1
2 30080 TN 2
我需要一个查询,该查询将返回显示在多个州的任何邮政编码。我怎样才能做到这一点?
SELECT zipcode
FROM (
SELECT zipcode
FROM temp
GROUP BY zipcode, state_abbr
) AS t
GROUP BY zipcode
HAVING COUNT(*) > 1
试试这个 sql。
MySQL 5.5.30 架构设置:
CREATE TABLE Table1
(`id` int, `zipcode` int, `state_abbr` varchar(2), `district` int)
;
INSERT INTO Table1
(`id`, `zipcode`, `state_abbr`, `district`)
VALUES
(1, 30080, 'GA', 1),
(2, 30080, 'TN', 2)
;
查询 1:
select zipcode
from Table1
group by zipcode
having count(zipcode)>1
结果:
| ZIPCODE |
-----------
| 30080 |
SELECT DISTINCT x.zipcode
FROM zipcode x
JOIN zipcode y
ON y.zipcode = x.zipcode
AND y.id < x.id;