Yuri Refolo
Yuri Refolo

Reputation: 245

insert child mysql

I've got a newbie question...

I've got two tables:

parentTable
-----------
id_user int(11) not null auto increment primary key,
email varchar(64),
pass varchar(64)

childTable
----------
id_user int(11) not null, 
name varchar(64), 
address varchar(512), 
foreign key (id_user) references parentTable(id_user) 
on update cascade 
on delete restrict

Now can I insert:

insert into childTable (id_user) select id_user from parentTable where id_user = '1'

But I just want to insert also name and address values.

Sorry for the newbie question, but I lurked for a day and found nothing.

Thank you in advance for your reply.

Upvotes: 1

Views: 76

Answers (1)

newfurniturey
newfurniturey

Reputation: 38416

The interesting part about your query is that you know the id_user you're trying to select to insert - it's in your WHERE clause.

If you will always know the id_user, you can skip the extra SELECT portion of the query and directly do:

INSERT INTO childTable (id_user, name, address) VALUES (1, 'some name', '123 test street');

If you, for some other reason, need the additional SELECT, you can append the name/address values directly into the field-list, like this:

INSERT INTO childTable (id_user, name, address)
    SELECT id_user, 'some name', '123 test street' FROM parentTable WHERE id_user = '1';

Upvotes: 2

Related Questions