postgresql:带有选择查询的 INSERT INTO 语句

sum*_*mmu 0 postgresql select insert nested-query

我必须在table现有client_id列中插入一些数据,所以我使用 select 和 insert

INSERT into 'my_table' (column1, client_id, column3) VALUES (val1,select distinct client_id from 'my_table', val3)

我需要来自同一个表的my_tableclient_id 并且我需要在插入语句中使用 client_ids。

SELECT DISTINCT client_id FROM my_table 给了我 113 个 client_id,所以我想使用上述方法为每个 113 个客户端插入一些行。

我做了这个查询

INSERT INTO client_notification_preferences (client_id, object_type , frequency,created_at,updated_at) SELECT DISTINCT client_id, 'ClientShipment',1, CURRENT_TIMESTAMP , CURRENT_TIMESTAMP FROM client_notification_preferences;

但这给了我这个错误 在此处输入图片说明

 create_table "client_notification_preferences", id: :uuid, default: "uuid_generate_v4()", force: :cascade do |t|
t.uuid     "client_id"
t.string   "object_type"
t.integer  "frequency"
t.datetime "created_at",  null: false
t.datetime "updated_at",  null: false
Run Code Online (Sandbox Code Playgroud)

结尾

SAE*_*AEI 5

如果 val1 和 val3 是变量,并且 client_id 是 my_table 中的一个字段,您可以从下面的代码中使用。

 INSERT into 'my_table' (column1, client_id, column3) select distinct val1, 
    client_id,val3 from 'my_table'
Run Code Online (Sandbox Code Playgroud)

例如

INSERT into 'my_table' (column1, client_id, column3) select distinct 1, client_id,2 from 'my_table'
Run Code Online (Sandbox Code Playgroud)