First, answers to your questions:
Q: Can this happen without creating inconsistency?
A: In the current structure this template allows data inconsistency (a telefone
without Cliente
, for example).
Is there any way the value of a primary key is the same as the value of a primary key of another table?
A: Yes, but in very specific cases . If you have an identifier in two tables of the same value, for all practical purposes you are identifying the same entity; in this case, why not just have a table?
Let's first analyze your data model. If I understood correctly, this would be a representation:
Accordingtothismodel,acontactisidentifiedbyatelephoneandisusedtouniquelyidentifyaCustomer.
Problemswiththistemplate:
- Whathappensifacustomerhas2ormorephones?
- Whathappensifacustomerhasemail,butnotaphone?
- Whathappensif2customerssharethesamephonenumber?
Yourtemplateneedstobeabstractenoughtocoverasmanytrivialsituationsaspossible.Anotheraspectistheprimarykeydefinition:avalue(or,alternatively,values)thatisnotrepeatedandthatuniquelyidentifiesarecordinitstable.Neitherphonenornamecoversthisspecification.
Step1:CreatingaID
fieldforuniquerecordid.
Create a field with a unique initialization (a numeric autocontroller or GUID
, for example) that will serve as the unique identifier for the record. Create a field in your contato
, Cliente_ID
table, and use it as a foreign key.
In this way you allow homonyms (which will have different IDs) and repeat phones without violating your model.
But it's still not good enough.
Step 2: Contact modeling by type
Create a table, Contact_Type, and store there any contact you need. For example:
Contato_Tipo
ID Descricao
1 Telefone
2 Fax
3 Email
Modify your Contato
table to, instead of storing a value of each type, now reference the ID
field of the Contato_Tipo
table via the foreign key Contato_Tipo_ID
. Store a single value there, in the Valor
column.
Let's simulate a Customer, Goku. Their telephone number is 555-4433, and their email is [email protected]. The values in the tables would be as follows:
Cliente
ID Nome
1 Goku
Contato
ID Cliente_ID Contato_Tipo_ID Valor
1 1 1 555-4433
2 1 3 [email protected]
This model has great advantages over the previous one. It allows 0-N values of 0-N types for each client; and when the need to add another type of contact appears (StackOverflow profile link, for example), you do not need to change its structure - just add another record to the Contato_Tipo
table.