我有3个表professionals
,services
和feature_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')
答案 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而不是静态值插入的方法:
答案 1 :(得分:0)
你不能在cte之后插入两个,所以将每个插入一个不同的cte
<强> SQL DEMO 强>
from django.db.models import Count
query = (Names.objects
.values('type')
.annotate(sum_value=Count('value'))