简体   繁体   中英

MYSQL Insert id from another table

i have the follow doubt

I have 2 tables:

id customers
1  alan
2  beth
3  john

and

id id_customers value
1  1            bar  
2  1            foo
3  2            baz

Example:I need to add the value 'alfa' in second table and link this to id 3 from the first.

How i do this?

Try this

insert into tab2 (id_customers, value)
values ((select id from tab1 where customers='john'), 'alfa');

Miss out brackets

Hope it helps

Wouldn't you just do an insert ?

insert into t2 (id_customers, value)
    values (3, 'alfa');

This assumes that id is auto-incrementing. If not, you'll need to assign that a value as well.

Based on your comment, use insert . . . select insert . . . select insert . . . select :

insert into t2 (id_customers, value)
    select id, 'alfa'
    from t1
    where name = 'john';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM