Relationship 0.. 1 in practice

Asked

Viewed 398 times

3

Having the following tables:

  • request
  • address
  • table

Orders can be made at the pizzeria, that is, for a table. It can be a delivery(address) or it can be a request for travel, where it does not belong to anyone. In the SQL of the requested table, I currently have the following:

CREATE TABLE pedido  
(  
cod_ped INT NOT NULL,  
cod_mesa INT,  
cod_end INT,  
val_ped DECIMAL(18,2),  
tipo_ped CHAR(1) NOT NULL,   
data_ins DATETIME,  
CONSTRAINT pk_cod_ped  
PRIMARY KEY(cod_ped),  
CONSTRAINT fk_cod_mesa  
FOREIGN KEY (cod_mesa)   
REFERENCES mesa(cod_mesa),  
CONSTRAINT fk_cod_end  
FOREIGN KEY (cod_end)   
REFERENCES endereco(cod_end),     
);

However, as explained, the same request may belong to either one desk/address or none at all. Creating the foreign key would be forcing this request to have an address and a desk. How to solve this problem?

1 answer

7


If a field is a foreign key, and at the same time can receive a null value, then it does not have to have value. However, if it has value, it must refer to the referenced table.

So, the way you created is right. Just send null value in the fields cod_mesa and cod_end which will be a request for travel.

Browser other questions tagged

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