Re: Are circular REFERENCES possible ?

Поиск
Список
Период
Сортировка
От Josh Berkus
Тема Re: Are circular REFERENCES possible ?
Дата
Msg-id web-97958@davinci.ethosmedia.com
обсуждение исходный текст
Ответ на Are circular REFERENCES possible ?  (Denis Bucher <dbucher@niftycom.com>)
Ответы Re: Are circular REFERENCES possible ?
Re: Are circular REFERENCES possible ?
Список pgsql-sql
Denis,

> I have a case where I wanted to do circular REFERENCES, is this
> impossible ?

It can be done.  It's just a bad idea.

> We deliver to the *shops* of our *customers*.
> We have therefore two tables :
>   - customers (enterprise, financial information, and so on...)
>   - shop (with a name, street, phone number, name of manager)
>
> Now, each shop REFERENCES a customer so that we know
> to which customer belongs a shop.
>
> AND, each customer has a DEFAULT shop for deliveries, i.e. most
> customers only have one shop, or a main shop and many small ones.
> Therefore a customer should REFERENCES the 'main' or 'default' shop.

You can do this by applying the constraints *after* table creation.
However, you will forever fight the following problems:

1. You will not be able to add any records to Customers without dropping
and re-creating the REFERENCES each time.
2. You will never be able to delete a record from either table due to
the circular reference check.
3. Some UPDATES will also fail for the same reason.

All of this makes circular references a bad idea; references are meant
to be heirarchical.  Heck, I got into a real mess when I accidentally
set up a circular reference among 5 tables ... took me forever to figure
out why INSERTS kept failing.

So, an alternate solution to your database structure:

1. Each Customer has one to many Shops (Shops.CustomerID REFERENCES
Customers(ID)).
2. Each Shop has a Boolean characteristic Default.
3. Of a Customer's shops, only one can have Default=TRUE at any one
time.

You use triggers or functions to enforce rule 3.  This system works
quite well for this purpose ... I was able to put it to use for a much
more complex CRM system with main and secondary HR and billing
addresses.

Your third alternative is to create a JOIN table called Default Shops.
However, this does not really provide you any additional referential
integrity -- it jsut may suit you if you find triggers intimidating.


-Josh


______AGLIO DATABASE SOLUTIONS___________________________
                                       Josh Berkus
  Complete information technology      josh@agliodbs.com
   and data management solutions       (415) 565-7293
  for law firms, small businesses        fax 621-2533
    and non-profit organizations.      San Francisco

Вложения

В списке pgsql-sql по дате отправления:

Предыдущее
От: Jan Wieck
Дата:
Сообщение: Re: Simple Insert Problem
Следующее
От: Vivek Khera
Дата:
Сообщение: Re: Adding an INTERVAL to a variable