简体   繁体   English

如何创建SQL查询以从另一个表插入值?

[英]How to create sql query to insert values from another table?

I have a table which related to another table by 1:1. 我有一张桌子,该桌子与另一张桌子的比例为1:1。 The first table called 'Deal' which has: id, deal_ext_id fields 第一个称为“交易”的表,其中包含:id,deal_ext_id字段
The second table called 'Deal_Ext' which has: id, externalId, systemId fields. 第二个表称为“ Deal_Ext”,它具有:id,externalId,systemId字段。

I also have temp table which contains externalId, systemId fields which need to be inserted to the second table (Deal_Ext). 我也有临时表,其中包含externalId,systemId字段,需要将其插入第二个表(Deal_Ext)。

Because the relation between both tables (Deal, Deal_Ext) is 1:1, the foreign need also be updated when values are inserted to 'Deal_Ext' table. 由于两个表之间的关系(Deal,Deal_Ext)均为1:1,因此在将值插入“ Deal_Ext”表中时也需要更新外部数据。

How can I have a for loop, which getting through my temp table and first insert new line to 'Deal_Ext' with new Id, second, by this new Id, I will update 'Deal' table accordingly? 我怎样才能有一个for循环,该循环遍历我的临时表,并首先使用新ID将新行插入到'Deal_Ext',其次,通过这个新ID,我将相应地更新'Deal'表?

Thanks! 谢谢!

Phase 1: 阶段1:
insert into deal_ext(external_id) select t.campaign_id from tempdeal t; 插入deal_ext(external_id)中,从模板t中选择t.campaign_id;

Phase 2: 阶段2:
update deal set deal_ext_id = (select e.id from tempdeal t, deal_ext e where t.campaign_id = e.external_id and t.deal_id = deal.id) 更新交易集deal_ext_id =(从临时交易t中选择e.id,在deal.ext e中选择e.id,其中t.campaign_id = e.external_id和t.deal_id = Deal.id)

Solved! 解决了!

您可以执行以下查询:

insert into tableone(col1,col2) select col1,col2 from table2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM