簡體   English   中英

MYSQL 從另一個表插入 id

[英]MYSQL Insert id from another table

我有以下疑問

我有2張桌子:

id customers
1  alan
2  beth
3  john

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

示例:我需要在第二個表中添加值 'alfa' 並將其鏈接到第一個表中的 id 3。

我怎么做?

嘗試這個

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

錯過括號

希望它有幫助

你不只是做一個insert嗎?

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

這假設id是自動遞增的。 如果沒有,您還需要為其分配一個值。

根據您的評論,使用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