1

我需要在我的数据库中插入大量的东西

以手写方式写出查询将是这样的(但有更多的东西!)

Insert into MyTable (country_id, event) values (1001, 'up')
Insert into MyTable (country_id, event) values (1001, 'down')
Insert into MyTable (country_id, event) values (1002, 'up')
Insert into MyTable (country_id, event) values (1003, 'down')
....
Insert into MyTable (country_id, event) values (9999, 'up')
Insert into MyTable (country_id, event) values (9999, 'down')

我可以编写某种神奇的 sql 连接/合并奇迹查询来获取所有country_ids和所有“事件”类型并创建我需要的数百个插入语句吗?

编辑:
有一个国家表。应该插入 MyTable 的是 sql 查询的结果,并且该查询的每个结果都需要 MyTable 中的“向上”和“向下”行。有足够的我不想手动管理查询。

实际上,不仅仅是“向上”和“向下”,但它们可以手动输入,或者作为进一步查询的结果。

4

4 回答 4

7

创建国家和事件列表的笛卡尔积并立即插入它们:

insert into MyTable (country_id, event)
select countries.country_id, 
       e.[event]
  from countries
 cross join
 (
   select 'Up' [event]
   union all
   select 'Down'
 ) e
于 2012-08-22T11:11:40.297 回答
2

你可以跳过

 Insert into MyTable (country_id, event) values 

并将其替换为

 Insert into MyTable (country_id, event) values (1001, 'down'),
 (1002, 'up'),
 (1003, 'down')

或者您可以查看BULK INSERT或者bcp您的数据是否来自文件。

或者如果你知道国家和事件是什么,

Insert MyTable (country_id, event) 
SELECT countryid, event 
FROM country, events

将所有组合放入您的表中

于 2012-08-22T11:00:03.623 回答
2

你可以这样加入VALUES

INSERT INTO MyTable (country_id, event) 
VALUES (1001, 'up'),(1001, 'down'),(1002, 'up'),(1003, 'down')
于 2012-08-22T11:01:09.770 回答
2

http://sqlfiddle.com/#!3/0355b/10

演示 SQL 小提琴

注意:两个表模式必须相同

于 2012-08-22T11:53:10.740 回答