Mysql Database (Insert Into and correct order)

0

My question may sound silly, but is it something I always miss, how to know the correct order of insert into the database? I was told that it is by foreign keys, but I did not understand logic

the insert was in that order:

post  crew mission function

status type of aircraft aircraft scale

    
asked by anonymous 13.02.2018 / 23:00

1 answer

0

The order for you to insert the data into the Table would be first by the tables that will be foreign ... For example, we have the TIMES table and the JOGADORES table:

CREATE TABLE TIMES 
(
    COD_TIME NUMBER(3) NOT NULL,
    NOME VARCHAR2(100) NOT NULL,

    CONSTRAINT PK_TIMES PRIMARY KEY (COD_TIME)
);

CREATE TABLE JOGADORES
(
    COD_JOGADOR NUMBER(3) NOT NULL,
    NOME VARCHAR2(100) NOT NULL,
    COD_TIME NUMBER(3) NOT NULL,

    CONSTRAINT PK_JOGADORES PRIMARY KEY (COD_JOGADOR),
    CONSTRAINT FK_TIMES_JOGADORES FOREIGN KEY (COD_TIME) REFERENCES TIMES
);

In our example, each player has a team: If we start to populate the tables by the JOGADORES table, there will be no teams, because we have not yet added any records to the TIMES table. In the image, I tried to add a JOGADOR with TIME of CODIGO = 1 , but it gave me an error, which happens because there is no CODIGO = 1 in the TIMES table, ie it's as if I was saying that a player is part of a team that does not yet exist.

FromthemomentIcreatedTIME,givingaINSERTintheTIMEStablewithaCOD_TIME=1record,thenyeswecanaddJOGADOR.

That is, by answering your question, you need to start the registry insertion for tables that do not have a FOREIGN KEY attached to them, unless you already have records in the foreign table.

In your case, in the AERONAVE table, you would not be able to add a AERONAVE without first adding the record to STATUS and TIPO_AERONAVE (unless these columns accept NULL).

    
14.02.2018 / 01:04