简体   繁体   English

MYSQL 从另一个表插入 id

[英]MYSQL Insert id from another table

i have the follow doubt我有以下疑问

I have 2 tables:我有2张桌子:

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.示例:我需要在第二个表中添加值 'alfa' 并将其链接到第一个表中的 id 3。

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吗?

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

This assumes that id is auto-incrementing.这假设id是自动递增的。 If not, you'll need to assign that a value as well.如果没有,您还需要为其分配一个值。

Based on your comment, use insert . . . select根据您的评论,使用insert . . . select insert . . . select insert . . . select : insert . . . select

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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