2012-11-12 85 views
1

我将数据插入到如下所示的数据库中: (1, 'blue'), (2,'large'), (3, 'round')插入期间从其他表中选择数据?

这里的数字对应于另一个表中的ID。看起来像这样:id | value

当插入这个数据时,我想插入数字对应的实际值,而不是id。

是否有任何查询要做到这一点?或者在将数据发送到数据库之前是否需要匹配这些值?

虽然我知道这是行不通的,我希望有这样的:
insert into table2 (table1.value[id=1], 'blue'), (table1.value[id=2],'large'), (table1.value[id=3], 'round') join table1

我想我可以使用:

insert into table2 
    ((select value from table1 where id=1), 'blue'), 
    ((select value from table1 where id=2),'large'), 
    ((select value from table1 where id=3), 'round') 

但随着比方说,40个不同的属性,这些属性会做41个查询!

回答

2

首先虚拟出一个你想要插入的值(id,value)的表格,然后将派生表格连接到table1并将结果插入到table2中。

insert into table2 
    select t.value, madeup.other 
     from (select 1 id, 'blue' other union all 
      select 2, 'large' union all 
      select 3, 'round') madeup 
     join table1 t on t.id = madeup.id; 
0

您可以使用临时表将id映射到值。我不是真的说MySQL,但是像这样:

create table #mapping (id int, description varchar) 
insert into #mapping values (1, 'blue') 
insert into #mapping values (2, 'large') 
insert into #mapping values (3, 'round') 

insert into table2 
select table1.value, #mapping.description 
from #mapping 
join table1 on table1.id = #mapping.id 

drop table #mapping 
相关问题