INSERT INTO后返回where条件的行数? PostgreSQL的

时间:2018-04-29 15:27:10

标签: postgresql

我有一个表重新组合了一些用户以及他们加入了哪个事件(如在IRL事件中)。

我已经设置了一个允许用户加入活动的服务器查询。

它是这样的:

INSERT INTO participations
VALUES(:usr,:event_id)

我希望该语句还返回与用户加入同一事件的人数。我该怎么办?如果可能,在一个SQL语句中。

由于

2 个答案:

答案 0 :(得分:1)

您可以使用这样的公用表表达式将其作为一个查询执行。

with insert_tbl_statement as  (

    insert into tbl values (4, 1) returning event_id
)
select (count(*) + 1) as event_count from tbl where event_id = (select event_id from insert_tbl_statement);

参见演示http://rextester.com/BUF16406

答案 1 :(得分:0)

您可以使用一个功能,我已经设置了下一个示例,但请记住,您必须在最终计数中添加1,因为仍然没有提交事务。

create table tbl(id int, event_id int);
insert into tbl values (1, 2),(2, 2),(3, 3);
3 rows affected
create function new_tbl(id int, event_id int)
returns bigint as $$

    insert into tbl values ($1, $2);

    select count(*) + 1 from tbl where event_id = $2;

$$ language sql;
select new_tbl(4, 2);
| new_tbl |
| ------: |
|       4 |

db<>小提琴here