如何使用单个Insert语句插入数十万条记录?

时间:2019-05-06 13:10:58

标签: sql postgresql

我需要在一个表中插入具有特定值的数千条记录。只有两列具有动态值的条件。

业务逻辑:我需要为所有客户的所有网站插入特定值。一个客户可以拥有一个或多个网站。

如果我要编写静态SQL,那么我的SQL将要插入10万条记录!

我要作为

插入表website_preferences中的记录
INSERT into website_preferences ( cid, website_id, key, value, is_preview, updated_by, updated_on, created_by, created_on, details )
VALUES ( DYNAMIC_CID, DYNAMIC_WEBSITE_ID, 'NEIGHBORHOOD_GOOGLE_PLACES', 'airport, gas_station, supermarket, gym', 123, NOW(), 123, NOW(), NULL )

websites表具有cid和website_id以及其他元数据。

此查询将给我多达数十万条记录:

SELECT w.id,w.cid FROM websites w WHERE deleted_by IS NOT NULL

如何从cid表中获取idwebsites(网站ID)并关联到insert语句?

3 个答案:

答案 0 :(得分:3)

使用insert . . . select

insert into website_preferences ( cid, website_id, key, value, is_preview, updated_by, updated_on, created_by, created_on, details )
    select ws.cid, ws.website_id, 'NEIGHBORHOOD_GOOGLE_PLACES', 'airport, gas_station, supermarket, gym', 123, NOW(), 123, NOW(), NULL
    from websites ws
    where ws.deleted_by is not null;

答案 1 :(得分:2)

看起来您正在寻找INSERT ...选择:

INSERT into website_preferences (cid, website_id, key, value, is_preview, updated_by, updated_on, created_by, created_on, details)
SELECT w.id, w.cid, 'NEIGHBORHOOD_GOOGLE_PLACES', 'airport, gas_station, supermarket, gym', 123, NOW(), 123, NOW(), NULL
FROM websites w 
WHERE deleted_by IS NOT NULL;

答案 2 :(得分:1)

您可以尝试以下方法:

INSERT into website_preferences ( cid, website_id, key, value, is_preview, updated_by, updated_on, created_by, created_on, details )
SELECT w.id,w.cid,'NEIGHBORHOOD_GOOGLE_PLACES', 'airport, gas_station, supermarket, gym', 123, NOW(), 123, NOW(), NULL FROM websites w WHERE deleted_by IS NOT NULL