创造城市,县,国家关系

时间:2013-07-08 17:59:32

标签: sql-server relation

我从here下载了此csv文件,其中包含以下内容:

数据库专栏:

ZIP
LATITUDE
LONGITUDE
CITY
STATE
COUNTY
ZIP_CLASS

现在我将其导入SQL Server,并且我有一个具有相同列的表。从该表中我创建了statescounty表,如下所示:

insert into states(name)
select distinct [state] from newlist order by state asc

insert into counties(name, stateid)
select distinct n.[county], s.id as stateid
from newlist n
inner join states s on n.[state] = s.name
order by county asc

现在,当我想创建一个cities表并与县id有关系的时候,我一直在找到许多重复项

Cities

select distinct n.[city], c.id as countyid
from newlist n
inner join counties c on n.[county] = c.name
order by city asc

原始表有大约30,000条记录,运行时它给了我超过140,000条记录。我看到它与该县处于不同的州有什么关系?如果需要,我可以附加SQL脚本与表结构和数据,如果这样可以更容易地帮助我解决这个问题。真的卡住了,不知道如何解决它。

1 个答案:

答案 0 :(得分:1)

有10个州有“橙县”。县表中的州是来自您的源数据,还是您通过名称推断它?

试试这个:

INSERT INTO Counties(name, stateid)
  SELECT DISTINCT LIST.name LIST.stateid
  FROM NewList  LIST

然后

 INSERT INTO Cities(city, countyid)
  SELECT DISTINCT LIST.city, COUNTY.countyid
    FROM NewList LIST
         INNER JOIN Counties COUNTY
            ON COUNTY.state = LIST.stateid
            AND COUNTY.name = LIST.county

这假设stateid是双字符状态代码