Mysql Database (Insert Into and correct order)

Asked

Viewed 1,338 times

0

my doubt may seem silly, but it is something that I always get lost, how to know the correct order of Insert into (to insert data in the table) in the database ? I was told it’s for the foreign keys, but I didn’t understand the logic

inserir a descrição da imagem aqui

The Serts were in that order:

post crew mission function

status typoaeronave aircraft stopover

  • Do you have any table structure to put next to the question?

  • Worst of all, I had this doubt, so I was putting the Serts and testing which one worked

  • So you have an example?

  • I have a bank here, but it’s very large, as you want me to send ?

  • Take a photo or print of the relational model.

  • Assemble a basic example here http://sqlfiddle.com/

  • edited the post with an example

Show 2 more comments

1 answer

1

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

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 popular the tables by the table JOGADORES, there will be no team, because we have not added any record in the table TIMES. In the image, I tried to add a JOGADORwith the TIMEof CODIGO = 1, but gave me a mistake, which happens because there is no CODIGO = 1on the table TIMES, I mean, it’s like I’m saying that a player is part of a team that doesn’t exist yet.

INSERINDO JOGADOR SEM EXISTIR O TIME From the moment I created the TIME, giving a INSERTon the table TIMESwith a record of COD_TIME = 1, then we can add the JOGADOR.

ADICIONANDO JOGADOR

That is, answering your question, you need to start inserting record by tables that do not have a FOREIGN KEYlinked to them, unless the foreign table already has records.

In your case, in the table AERONAVE, it would not be possible to add a AERONAVEwithout first adding registration in STATUS and in TIPO_AERONAVE(Unless those columns accept NULL).

  • Now I understand, thank you very much Richard Willian!

  • You’re welcome, we need you/

Browser other questions tagged

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