0
How do I make a insert into
in a table where there is a FK?
example this is my structure
Pessoa
ID (primary key)
nome varchar(20)
id_endereco int not null (foreign key)
_______________________________________
endereco
ID (primary key)
rua varchar(50)
_______________________________________
in SQL I did
create table endereco (
ID int primary key NOT NULL,
rua varchar(50)
);
create table pessoa (
ID int primary key NOT NULL,
nome varchar(50) NOT NULL,
id_endereco int NOT NULL,
CONSTRAINT fk_idendereco FOREIGN KEY(id_endereco) REFERENCES pessoa(ID)
)
Then in the activity asks me, add 20 people... the problem is that when I use "Insert into person" I can’t add the 20 people because of Foreign key, if I didn’t have it, I could get it good.. but as it exists in table person, appears that error.
Is there any way I can add in the person table, there is nothing in the address? if not, what do I do?
insert into pessoa (id,nome,id_endereco)
values (1, "Jo Legendary", 1)
Put the SQL code you are using to do the
INSERT
. Probably the column does not accept NULL.– João Martins
Apparently, the FK does not exist, since the outta table has no record with this foreign field. Enter your code to make it easier to identify.
– Renato Junior
You first have to do the
insert
on the tableendereco
, rescue theid
and use it to insert the record in the tablecliente
.– Roberto de Campos
Place the structure of your table
endereco
.– Roberto de Campos
@Robertodecampos ready, I more or less refined what I wanted to explain.. sorry, when I asked the question was 5 am I was very tired hehe
– PLegendary
@Joãomartins yes, the column cannot accept null (I edited the question) in this case it is mandatory to have the address to create the person? , in this activity as I do to add a person with that fk to the address id?
– PLegendary
@RORSCHACH Good morning! ready put the problem structure and sql I made :D
– PLegendary
Basically cannot insert a record in the table
pessoa
without first having a record in the tableendereco
.– João Martins
@Joãomartins right, so in case I do an Insert in the 'address' by adding an ID and a street, and then I do the person’s Insert by putting id, name, and address id? is that as the activity was to add the person, I didn’t know I had to do address first... because in question 1 it was add '5' people and in question 3 it was add '5' addresses.
– PLegendary
@Jolegendary maybe the teacher did it anyway so you realize it doesn’t work that way.
– Jorge B.
@Jolegendary can see his
INSERT
?– Jorge B.
hi @Jorgeb. thanks for commenting, put at the end of the question as more or less I tried the Insert in the person table... any suggestions? (I’m learning sql now)
– PLegendary