![](/img/trans.png)
[英]How can i use SQL Select Insert to copy rows from one table to another
[英]How can I copy rows from one to another table with a different number of columns
我在MySQL语法上有一个“异常”问题。
我有2张桌子:
table1:商品
id_commodity
,具有7列id
,id_commodity
,parameter
,value
,units
,type
,notes
table2:trade_commodity,具有8列
id
,id_trade
,id_commodity
,parameter
,value
,units
,type
,notes
注意:两个表的主键都是'id',这是我不想复制的
我想要的是将所有列从表1复制到表2,而且还要在表2中为id_trade
创建值。
请查看table1和table2的列数不同,并且table2上的id_trade
不是auto_increment。
这是实际结果和期望结果的示例:
table1:
id,id_commodity,parameter,value,units,type,notes
1, 1, 'Ash','10','%','min','ash for a commodity'
2, 1, 'Ash 2','15','%','max','ash for a commodity'
完成复制过程后,将产生:
table2:
id,id_trade,id_commodity,parameter,value,units,type,notes
1,NULL,1, 'Ash','10','%','min','ash for a commodity'
2,NULL,1, 'Ash 2','15','%','max','ash for a commodity'
我想要的是table2的结果:
id,id_trade,id_commodity,parameter,value,units,type,notes
1,10,1, 'Ash','10','%','min','ash for a commodity'
2,10,1, 'Ash 2','15','%','max','ash for a commodity'
id_trade的值为'10'
来自php var。
我该怎么做? 还是还有另一个棘手的问题? 顺便说一句,我正在使用PHP和MySQL来完成此任务。
编辑:我看到与此“类似”的问题,但我发现他正在尝试使用命令而不是值MYSQL:如何在mysql中将整个行从一个表复制到另一个表中,而第二个表又有一个额外的列?
请帮助我,谢谢。
这项工作:
insert into table2 (id_commodity,parameter,value,units,type,notes)
select id_commodity,parameter,value,units,type,notes
from table1
更新:鉴于OP提供的其他信息,这应该是OP寻找的解决方案:
insert into table2 (id_trade, id_commodity,parameter,value,units,type,notes)
select '10', id_commodity,parameter,value,units,type,notes
from table1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.