【问题标题】:Insert with returning a subquery插入并返回子查询
【发布时间】:2016-09-06 12:33:55
【问题描述】:

我正在尝试在 m:n 表(用户组关系)中插入一条记录,并在用户成功加入时返回组。

但我无法在插入后返回整个组。

with "group" as (
    SELECT * from "group" where code = 'tohubo' LIMIT 1
)
insert into group_users__user_groups ("group_users", "user_groups")
    select id from "group", 1 
returning (SELECT * from "group")

通过该查询,我目前收到错误消息

子查询必须只返回一列

我也试过只返回 *,但后来我只得到了 group_users__user_groups 的内容。

我还尝试在末尾添加一个额外的 Select:

with "found_group" as (
    SELECT * from "group" where code = 'tohubo' LIMIT 1
)
insert into group_users__user_groups ("group_users", "user_groups")
    select 1, id from "found_group";
Select * from "found_group";

但是第二个查询中没有定义 WITH 部分:

内核错误:错误:关系“found_group”不存在

【问题讨论】:

  • 在Oracle中,我们需要先写Insert,然后是with,然后是select,来自表或内联表名。检查一次是否还需要进行类似的更改。
  • select id from "group", 1 这部分不清楚 - 你是不是想用 1 加入“组”?...因为如果你想插入两个值,它应该是 select id,1 from "group"
  • btw postgresql.org/docs/9.5/static/sql-insert.html 所以并不是要在返回 *?.. 时返回这两列

标签: sql postgresql postgresql-9.5


【解决方案1】:

returning 子句只能返回受插入影响的数据。

您在 CTE 中只能有一个“最终”语句,而不是插入选择。

但是您可以简单地将插入移动到第二个 cte,然后在末尾有一个 SELECT 来返回找到的数据

with found_group as (
    SELECT * 
    from "group" 
    where code = 'tohubo' 
    LIMIT 1
), inserted as (
   insert into group_users__user_groups (group_users, user_groups)
   select 1, id 
   from found_group
)
Select * 
from found_group;

【讨论】:

  • 如何在最终的select * from found_group 中返回插入的group_users 值(= 1)?
猜你喜欢
  • 2011-07-16
  • 2011-12-28
  • 1970-01-01
  • 2017-03-03
  • 1970-01-01
  • 1970-01-01
  • 2013-02-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多