基于从另一个表中提取的数据的SQL大量插入

时间:2011-02-27 06:03:26

标签: mysql sql

我真的不知道我的说法是否正确,但我会试着解释一下我想要的东西。

Table 1 - X
id | name | blah

Table 2 - Y
id | Xid | configKey | ConfigVal

我想要做的是,在表2中为表1中的所有内容创建一行,其中表1中的相应id进入表2中的Xid列。我来自java背景而不是太热衷于sql,所以不太确定如何做到这一点。表1中有很多行,这就是我想编写脚本的原因。

我非常想做这样的事情:

Table1 (the object table)
1 test1 a
2 test3 b
3 testn n

运行查询以填充此

Table 2 (the config table)
...exisitng rows
59 1 doSomething true
60 2 doSomething true
61 3 doSomething true

所以,我非常想添加一个配置行(所有相同的值),除了它对应的id(表2中的第2列应该是表1中的col 1)

由于

3 个答案:

答案 0 :(得分:4)

对所有插入的记录使用固定值'doSomething'和'true':

insert into table2 (Xid, configKey, ConfigVal)
select id, 'doSomething', 'true'
from table1

答案 1 :(得分:3)

使用Select Into该链接是SQL Server语法,语法因服务器而异,但格式通常非常接近。

SQL Server

 select id as Xid, value as name, 'other value' as blah  INTO TABLE1 from TABLE2

我的SQL

 INSERT INTO table1 (id, name,other_value)
SELECT xid, value, 'another value' as other_value from TABLE2

以下是SQL Tutorial引导您完成整个过程。

答案 2 :(得分:0)

我认为这可能有效

Insert into table2(xid, value)
select id, name from table1.

但是您必须将table2中的Id列作为标识,或者必须为其指定默认值。 (但这仅适用于sql server。)