[英]how do i get the return value in json after inserting in sql?
我想要json中的返回值
INSERT INTO games (player, score)
VALUES("john", 42) returning *
給了我新創建的行,但我想要 json 格式,所以下面失敗
INSERT INTO games (player, score)
VALUES("john", 42) returning json_agg(*)
它是如何正確完成的?
不要使用 json_agg 使用to_jsonb()
:
INSERT INTO games (player, score)
VALUES ('john', 42)
returning to_jsonb(games);
如果要插入多行和一個單一的大JSON數組,你需要包裝成CTE這樣的:
with new_games as (
insert into games (player, score)
values ('john', 42), ('peter', 50)
returning *
)
select jsonb_agg(to_jsonb(ng))
from new_games ng;
似乎您可能正在尋找ROW_TO_JSON()
函數:
WITH r AS
(
INSERT INTO games (player, score)
VALUES('john', 42)
RETURNING *
)
SELECT ROW_TO_JSON(r)
FROM r;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.