如何使用子查询作为值之一插入多行?

时间:2018-12-05 00:59:37

标签: sql postgresql

我正在尝试向表中插入多行,其中一列的值来自另一查询。但是我遇到了以下错误

  

由子查询返回的多于一行用作表达式

我应该怎么做?

INSERT INTO 
   accounts_account_preferences (account_id, preference_id) 
VALUES 
   ((SELECT account_id 
     FROM accounts_account_preferences 
     WHERE preference_id = 1), 2);

2 个答案:

答案 0 :(得分:3)

使用INSERT ... SELECT ...而不使用VALUES

INSERT INTO accounts_account_preferences (account_id, preference_id) 
SELECT account_id, 2 
FROM accounts_account_preferences 
WHERE preference_id = 1

答案 1 :(得分:0)

您的内部查询应该为每个外部行返回1条记录。如果返回的记录多于一条,那么它将无法正常工作。