Question : Using a "primary" FK

Sorry about the less-than-descriptive title.  I'm having a hard time putting the issue into words.

Let's say I have a table CUSTOMERS that has just 2 columns: ID and NAME

And I have another table ADDRESSES that has standard address information (street, city, state, zip, etc) and an FK to CUSTOMERS (for this example, I'll call it CUSTOMER_FK).  Any customer can have multiple addresses.

I wanted to assign one row from ADDRESSES to be the billing/default/"primary" address for a customer.  A customer should only have one billing/default/primary address.

My initial thought was to add a column to CUSTOMERS called BILLING_ADDRESS that was an FK to the row in ADDRESSES that served as the billing/default/primary address.  This seems slightly redundant, though, and more importantly makes insertion a little less than elegant.  On creating a new customer from user input, for example, I'd have to create the CUSTOMERS row first, grab that ID, then create the ADDRESSES row (passing the CUSTOMERS ID just generated to CUSTOMER_FK), then go back and update the CUSTOMERS row with the ID of the newly created ADDRESS to serve as the FK for the billing/default/primary address.

Another thought was to, instead of the above, add a column to ADDRESSES that was a boolean indicator of whether or not the row was the billing/default/primary address for that customer, but AFAIK there's no way to ensure this is limited to a single address for any customer.

I'm guessing this isn't that rare, and there's probably a built-in solution that I'm not aware of.  If not, is there a more straightforward solution anyone could suggest?

TYIA

Using MySQL 5 (and PHP 5.3, if that matters).

Answer : Using a "primary" FK

I think...

add field ADDRESSTYPE to the ADDRESSES table (this field will be used to denote the type of address -- billing/default/primary -- you can use 1/2/3 for short)

then run this command:

ALTER TABLE ADDRESSES ADD UNIQUE (CUSTOMER_FK, ADDRESSTYPE);

back up everything first!

That should make the COMBINATION of customer/address type unique...
Random Solutions  
 
programming4us programming4us