使用另一个选择查询的结果将数据插入表中

mmd*_*del 45 mysql select insert

我寻求帮助的以下问题:我有两个表 Table_1itemid,locationid,quantity

Table_2itemid,location1,location2,location3

我想将数据从Table_1(仅quantity列)复制到Table_2(进入location1列).将itemid在这两个表相同的(Table_1有重复项的ID),所以这就是我要复制到新表,并保持在一个单一的行中的所有数量与每个位置为一列的原因.我使用以下查询但它不起作用

INSERT INTO 
Table_2(location1) 
(
 SELECT qty 
 FROM Table_1 
 WHERE locationid = 1 AND Table_1.locationid = Table_2.locationid
)
Run Code Online (Sandbox Code Playgroud)

Azi*_*ikh 96

如果table_2为空,则尝试以下insert语句:

insert into table_2 (itemid,location1) 
select itemid,quantity from table_1 where locationid=1
Run Code Online (Sandbox Code Playgroud)

如果table_2已包含itemid值,请尝试以下更新语句:

update table_2 set location1=
(select quantity from table_1 where locationid=1 and table_1.itemid = table_2.itemid)
Run Code Online (Sandbox Code Playgroud)

  • 如果您具有相同的列,那么就足够了:`insert into table_2 select itemid,quantity from table_1 where locationid = 1` (2认同)