Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Foreign keys on permutation table?

Author  Topic 

aiken
Aged Yak Warrior

525 Posts

Posted - 2003-03-28 : 03:55:34
Say I've got the following:
CREATE TABLE postal_codes (i int IDENTITY,code varchar(12) NOT NULL)

CREATE TABLE postal_code_distances (i_postal_codes_1 int NOT NULL,i_postal_codes_2 int NOT_NULL,distance smallint NOT NULL)


...as you can see, it's a simple way to precompute the distances between postal (zip, in the US) codes.

Now, obviously, I don't want to have two copies of everything, so what I'm doing is ensuring that _1 is smaller than _2 both during the precompute and query phases. So the table distance table looks like:

i_postal_codes_1 i_postal_codes_2 distance
1 2 35
1 3 15
1 4 88
1 5 65
2 3 76
2 4 11
3 4 81
3 5 91


...and so on. App code determines that the distance is 0 for identical postal codes, and for any given lookup it flips the values if necessary so the smaller one is queried against _1 and the larger one against _2.

So far so good. It works, it's fast, it's not too unmanageably big. But I'm at a loss for defining foreign keys -- should both _1 and _2 reference the identity from postal_codes? This is probably a simple, stupid question, but it's my first time dealing with a table that has two columns referencing the same column in another table.

(And, don't even *start* with the identity issue . I need to support varchar(12) postal codes today, and quite possibly nvarchar(50) postal codes tomorrow, and with the potential for well over a billion rows, the space and performance savings of doing it with an INT are significant).

Thanks in advance
-b

robvolk
Most Valuable Yak

15732 Posts

Posted - 2003-03-28 : 07:07:27
quote:
But I'm at a loss for defining foreign keys -- should both _1 and _2 reference the identity from postal_codes? This is probably a simple, stupid question, but it's my first time dealing with a table that has two columns referencing the same column in another table
Oh yeah, that's normal, and it's pretty easy:

CREATE TABLE postal_codes_distances(i_postal_codes_1 int NOT NULL
CONSTRAINT FK_PostalCode1 REFERENCES postal_codes(i),
i_postal_codes_2 int NOT NULL
CONSTRAINT FK_PostalCode2 REFERENCES postal_codes(i),
distance smallint NOT NULL)


Go to Top of Page
   

- Advertisement -