![](/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.