多个实例的数据库查询

时间:2013-06-13 12:17:06

标签: sql database

我有一个包含所有美国邮政编码及其相应的州和国会区的数据库表,如下所示..

id | zipcode | state_abbr | district
 1     30080      GA           1
 2     30080      TN           2

我需要一个查询,它将返回显示在多个状态的任何zipcodes。我怎么能这样做?

由于

3 个答案:

答案 0 :(得分:2)

SELECT zipcode 
FROM (
       SELECT zipcode 
       FROM temp
       GROUP BY zipcode, state_abbr 
     ) AS t 
GROUP BY zipcode 
HAVING COUNT(*) > 1

答案 1 :(得分:1)

试试这个sql。

SQL Fiddle

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

<强> Results

| ZIPCODE |
-----------
|   30080 |

答案 2 :(得分:0)

SELECT DISTINCT x.zipcode 
  FROM zipcode x 
  JOIN zipcode y 
    ON y.zipcode = x.zipcode 
   AND y.id < x.id;