First, answers to your questions:
P: This can happen without creating inconsistency?
A: In the current structure this model allows data inconsistency (one telefone
without Cliente
, for example).
P: there is some way the value of a primary key is the same value of a primary key of another table?
R: Yes, but in very specific cases. If you have an identifier in two tables with the same value, for all practical purposes you are identifying the same entity; in this case, why not have only one table?
We will initially analyze your data model. If I understood correctly, this would be a representation:
According to this model, a contact is identified by a telephone, and this is used to uniquely identify a Customer.
Problems with this model:
- What happens if a customer owns 2 or more phones?
- What happens if a customer has email, but doesn’t call?
- What happens if 2 customers share the same phone number?
Your model needs to be abstract enough to cover as many trivial situations as possible. Another aspect is the definition of the primary key: a value (or, alternatively, values) that does not repeat itself and uniquely identifies a record in its table. Neither phone nor name cover this spec.
Step 1: The creation of a field ID
for exclusive identification of the registration.
Create a field specifically with single initialization (a numerical autocomperer or GUID
, for example) which will serve as the unique identifier of the record. Create a field in your table contato
, Cliente_ID
, and use it as a foreign key.
This way you allow homonyms (who will have different Ids) and repeat phones, without violating your model.
But it’s still not good enough.
Step 2: Modeling of contacts by type
Create a table, contact type, and store all the contact types you need there. For example:
Contato_Tipo
ID Descricao
1 Telefone
2 Fax
3 Email
Modify your table Contato
to, instead of storing a value of each type, now reference the field ID
table Contato_Tipo
via the foreign key Contato_Tipo_ID
. Store a single value there in the column Valor
.
We will simulate a Client, Goku. Your phone number is 555-4433, and your 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 one more contact type appears (Stackoverflow profile link for example), you don’t need to change its structure - just add one more record to the table Contato_Tipo
.
"Is there any way that the value of a primary key is the same value as a primary key of another table?" If the primary key of one is also foreign key in the primary key of the other, then that is exactly what will happen; the values will necessarily be the same (assuming for each row in the table
contato
you add after a row in the tablecliente
).– mgibsonbr