How to create a Foreign key and Unique attribute at the same time?

Asked

Viewed 678 times

1

I would like to know whether there is any way, or how best, of restricting a relationship between two entities, one of which cannot be repeated in this relationship. I have the tables 'Customers' and 'Phone'. However 1 customer can have several phones, so I made a 'Customers' list. The problem is that you can’t repeat the phone number, but it has to exist on

tabela telefones.`create table cliente(
    cod_cli int primary key,
    nome varchar(40)
);

create table telefone(
    identificador int primary key,
    numero int unique
);

 create table cliente_telefone(
    id_cli_tel int primary key,
    cod_cli int,
    identificador int,
    constraint fk_cli foreign key(cod_cli) references cliente(cod_cli),
    constraint fk_tel foreign key(identificador) references telefone(identificador)
);
  • If the client can only have one phone, there is no need for the auxiliary table [cliente_phone], just add the column and Foreign key in the client table.

  • Hello @Wéllingthon M. de Souza. In my case I mentioned that the customer can have several phones, but in this table of relation, the phone id can repeat only once. It is as if the attribute 'identifier' (id_phone) was Foreign key and Unique at the same time in the cliente_phone table.

1 answer

2


  • This answer is wrong.

  • The field would be "identifier", it would be simpler the phone to be the key itself.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.