MYSQL从另一个表插入id

时间:2017-06-01 02:12:04

标签: mysql sql

我有疑问

我有两张桌子:

id customers
1  alan
2  beth
3  john

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

示例:我需要在第二个表中添加值'alfa'并将其链接到第一个表中的id。

我是怎么做到的?

2 个答案:

答案 0 :(得分:2)

试试这个

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

错过括号

希望有所帮助

答案 1 :(得分:0)

你不是只做insert吗?

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

这假设id是自动递增的。如果没有,您还需要分配一个值。

根据您的评论,使用insert . . . select

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