Как осуществить целостность БД с групповыми внешними ключами?

Существуют некоторые большие статьи о CodeProject:

http://www.codeproject.com/KB/library/IntroducingLucene.aspx
http://www.codeproject.com/KB/aspnet/lucene-net-in-asp-net.aspx
http://www.codeproject.com/KB/cs/lucene_analysis.aspx
http://www.codeproject.com/KB/cs/lucene_custom_analyzer.aspx

существует больше при вводе Lucene в их поиск.

Hope это помогает.

5
задан DzinX 10 October 2009 в 09:38
поделиться

8 ответов

В родительской таблице создайте уникальное ограничение на (идентификатор, версия). Добавьте столбец версии в свою дочернюю таблицу и используйте проверочное ограничение, чтобы убедиться, что он всегда равен 0. Используйте ограничение FK для сопоставления (родительской, версии) с родительской таблицей.

5
ответ дан 14 December 2019 в 04:42
поделиться

Alternatively you could maintain a person history table for the data that has historic value. This way you keep your Persons and Dogs table tidy and the references simple but also have access to the historically interesting information.

2
ответ дан 14 December 2019 в 04:42
поделиться

I would use and association table to link the many versions to the one pk.

0
ответ дан 14 December 2019 в 04:42
поделиться

Okay, first thing is that you need to normalize your tables. Google "database normalization" and you'll come up with plenty of reading. The PERSONS table, in particular, needs attention.

Second thing is that when you're creating foreign key references, 99.999% of the time you want to reference an ID (numeric) value. I.e., [DOGS].[owner] should be a reference to [PERSONS].[id].

Edit: Adding an example schema (forgive the loose syntax). I'm assuming each dog has only a single owner. This is one way to implement Person history. All columns are not-null.

Persons Table:
int Id
varchar(30) name
...

PersonHistory Table:
int Id
int PersonId (foreign key to Persons.Id)
int Version (auto-increment)
varchar(30) name
...

Dogs Table:
int Id
int OwnerId (foreign key to Persons.Id)
varchar(30) name
...

The latest version of the data would be stored in the Persons table directly, with older data stored in the PersonHistory table.

1
ответ дан 14 December 2019 в 04:42
поделиться

A project I have worked on addressed a similar problem. It was a biological records database where species names can change over time as new research improved understanding of taxonomy.

However old records needed to remain related to the original species names. It got complicated but the basic solution was to have a NAME table that just contained all unique species names, a species table that represented actual species and a NAME_VERSION table that linked the two together. At any one time there would be a preferred name (ie the currently accepted scientific name for the species) which was a boolean field held in name_version.

In your example this would translate to a Details table (detailsid, otherdetails columns) a link table called DetailsVersion (detailsid, personid) and a Person Table (personid, non-changing data). Relate dogs to Person.

0
ответ дан 14 December 2019 в 04:42
поделиться

Persons

id (int),
name,
.....
activeVersion (this will be UID from personVersionInfo)

note: Above table will have 1 row for each person. will have original info with which person was created.

PersonVersionInfo

UID (unique identifier to identify person + version),
id (int),
name,
.....
versionId (this will be generated for each person)

Dogs

DogID,
DogName
......

PersonsWithDogs

UID,
DogID

EDIT: You will have to join PersonWithDogs, PersionVersionInfo, Dogs to get the full picture (as of today). This kind of structure will help you link a Dog to the Owner (with a specific version).

In case the Person's info changes and you wish to have latest info associated with the Dog, you will have to Update PersonWithDogs table to have the required UID (of the person) for the given Dog.

You can have restrictions such as DogID should be unique in PersonWithDogs.
And in this structure, a UID (person) can have many Dogs.

Your scenarios (what can change/restrictions etc) will help in designing the schema better.

0
ответ дан 14 December 2019 в 04:42
поделиться

Благодаря ответу Майкла Гаттузо я обнаружил еще один способ описания этих отношений. Есть два решения, это второе из них. Пожалуйста, проголосуйте, какой из них вам больше нравится.

Решение 2

В таблице PERSONS мы оставляем только имя (уникальный идентификатор) и ссылку на данные первого (устаревшего!) Человека:

TABLE PERSONS:
    name:            varchar(30),
    first_data_id: int

Мы создаем новую таблицу PERSONS_DATA, которая содержит всю историю данных для этого человека:

TABLE PERSONS_DATA:
    id:      int
    name:    varchar(30)
    version: int (auto-generated)
    ... // some data, like address, etc.

Таблица DOGS остается прежней, она по-прежнему указывает на имя человека (таблица FK в PERSONS).

ПРЕИМУЩЕСТВА:

  • для каждой собаки существует как минимум одна строка PERSONS_DATA, содержащая данные ее владельца (это то, что я хотел)
  • , если я хочу изменить данные человека, мне не нужно обновлять строку PERSONS, только добавить новую PERSONS_DATA строка

НЕДОСТАТКИ:

0
ответ дан 14 December 2019 в 04:42
поделиться

Благодаря ответу Майкла Гаттузо я обнаружил еще один способ описания этих отношений. Есть два решения, это первое из них. Пожалуйста, проголосуйте, какой из них вам больше нравится.

Решение 1

В таблице PERSONS мы оставляем только имя (уникальный идентификатор) и ссылку на текущие данные человека:

TABLE PERSONS:
    name:            varchar(30),
    current_data_id: int

Мы создаем новый таблица PERSONS_DATA, которая содержит всю историю данных для этого человека:

TABLE PERSONS_DATA:
    id:      int
    version: int (auto-generated)
    ... // some data, like address, etc.

Таблица DOGS остается прежней, она по-прежнему указывает на человека » s имя (таблица FK в PERSONS).

ПРЕИМУЩЕСТВО: для каждой собаки существует как минимум одна строка PERSONS_DATA, содержащая данные ее владельца (это то, что я хотел)

НЕДОСТАТК: если вы хотите изменить данные человека , вам необходимо:

  1. добавить новую строку PERSONS_DATA
  2. обновить запись PERSONS для этого человека, чтобы он указывал на новую строку PERSONS_DATA.
0
ответ дан 14 December 2019 в 04:42
поделиться
Другие вопросы по тегам:

Похожие вопросы: