Вопрос

Backstory: To help my app quickly calculate the crow-flies distance between two zips (and also Google Map's distance..), I am storing the data in a table with essentially three columns: ZipCode1, Zipcode2 and Distance.

I have another table in my database named Zipcodes that contains all U.S. zip codes.

I would like to "pre-fill" my distance table with all unique "pairs" of zip codes. Since I don't want duplicate pairs, ZipCode1's integer value should always be less than ZipCode2.

So, that leaves me with the conundrum of figuring out the quickest/best way to do this. Bonus points if there's also a way to re-run the method to just add the missing pairs.

If I was coding this in C#, it would be trivial write out, but would run very slowly (as far as I can tell). There must be some quicker method, perhaps via direct SQL?

Any help/ideas are appreciated.

Это было полезно?

Решение

Try the below query, which should generate all the pairs and insert them all into target table in one go:

INSERT INTO ZipcodePairs (Zipcode1, Zipcode2)
SELECT z1.Zipcode, z2.Zipcode
  FROM Zipcodes z1
  JOIN Zipcodes z2 ON (z1.Zipcode < z2.Zipcode);

Другие советы

Try this...

INSERT INTO YOUR_DISTANCE_TABLE
(ZIPCODE1, ZIPCODE2)
SELECT A.ZIPCODE, B.ZIPCODE FROM ZIPCODES A
CROSS JOIN ZIPCODES B
WHERE A.ZIPCODE<B.ZIPCODE
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top