PostgreSQL一次插入2个关系

时间:2017-10-19 19:31:06

标签: sql postgresql

我有3个表professionalsservicesfeature_professional我需要在插入professional时插入数据。这是我试过的SQL。

WITH professionals as (INSERT INTO professionals(id, company_id, first_name) 
VALUES (1, 1, 'peter') RETURNING *) 

INSERT INTO services(id, professional_id, name) 
VALUES (1, (select professionals.id from professionals), 'haircut'),

INSERT INTO feature_professional(id, professional_id, feature_id, enabled) 
VALUES
    (1, (select professionals.id from professionals), 1, true)

我也试过这种包装括号内所有插入语句的不同变体,但仍然没有运气。我得到的错误是syntax error

ERROR:  syntax error at or near "INSERT"
LINE 106: INSERT INTO feature_professional

完成此操作的正确语法是什么?我知道如果我取出第三个insert语句,查询就可以了。例如:

WITH professionals as (INSERT INTO professionals(id, company_id, first_name) 
VALUES (1, 1, 'peter') RETURNING *) 

INSERT INTO services(id, professional_id, name) 
VALUES (1, (select professionals.id from professionals), 'haircut')

2 个答案:

答案 0 :(得分:0)

INSERT INTO feature_professional (id, professional_id, feature_id, enabled) 
select ?, professionals.id from professionals, ?, ?

如果问号是您可以插入的值。如果他们不是必需的,你可以省略它们。

INSERT INTO feature_professional (professional_id) 
select professionals.id from professionals

以下是从select而不是静态值插入的方法:

https://www.w3schools.com/sql/sql_insert_into_select.asp

答案 1 :(得分:0)

你不能在cte之后插入两个,所以将每个插入一个不同的cte

<强> SQL DEMO

from django.db.models import Count

query = (Names.objects
              .values('type')
              .annotate(sum_value=Count('value'))