我有一张桌子,比如说,桌子 list

unique_id next_id randomCol1
4 5 string 1
5 6 string 2
6 0 string 3

Where unique_id is auto increment column and next_id is the unique_id of the row it is pointing to. At present we have 4->5->6->0(0 is a Non existing row). Now I want to do an insertion of a row next to a given unique_Id, Let's say next to unique_Id=4.
At the time of insertion I want to extract the next_id(5) of the given unique_id(here, 4). The row which I'm about to insert will have next_id = 5 and row with unique_id = 4 will update its next_id to 7 (or whatever unique_id was generated at the time of insertion) So, My table will look like : 4->7->5->6->0

unique_id next_id randomCol1
4 7 string 1
5 6 string 2
6 0 string 3
7 5 string 4

我试过:

Insert into tableList(randomCol1,next_id)
values('string 4', select next_id from tableList where unique_id=4) returning unique_id as current_ID 
Update tableList set next_id = current_id where unique_id=4

说明:我正在try 插入randomCol1和next\u id,其中next\u id需要从给定的unique\u id中 Select .因此,有一个子查询.我想用插入同一查询后返回的任何unique\u id更新给定unique\u id的下一个\u id.

推荐答案

demo:db<>fiddle

您可以使用由WITH个子句组成的链:

WITH select_part AS (       -- 1
    SELECT next_id
    FROM tableList
    WHERE unique_id = 4
),
insert_part AS (            -- 2
    INSERT INTO tableList ("next_id", "randomCol1")
        SELECT next_id, 'my new string'
        FROM select_part
    RETURNING unique_id
)
UPDATE tableList t          -- 3
SET next_id = i.unique_id
FROM (
    SELECT * 
    FROM insert_part
) i
WHERE t.unique_id = 4
  1. SELECTunique_id = 4行中的next_id
  2. INSERT语句中使用此值并返回新生成的id.
  3. 使用新id将原始行设置为UPDATE.

然而,您可能会考虑使用单独的函数来实现这一点.

demo:db<>fiddle

CREATE OR REPLACE FUNCTION insert_value (
    _unique_id int, 
    _my_string text
) RETURNS void
AS $$
DECLARE 
    _next_val int;
    _new_id int;
BEGIN
    SELECT
        next_id
    FROM tableList
    WHERE unique_id = _unique_id
    INTO _next_val;
        
    INSERT INTO tableList("next_id", "randomCol1")
    VALUES (_next_val, _my_string)
    RETURNING unique_id
    INTO _new_id;
    
    UPDATE tableList t
    SET next_id = _new_id
    WHERE unique_id = _unique_id;
END;
$$ LANGUAGE plpgsql

请使用以下选项进行调用:

SELECT insert_value(4, 'my_string');

Sql相关问答推荐

postgresql插入json不工作

我如何计算字母a出现的字符串的次数?

在多个柱上连接时,如何确定连接条件?

Access 365将文本转换回BigInt

为什么在postgres中,横向连接比相关子查询快?

用户购买平台及金额统计

带上最后日期(结果)

在MS Access Modern图表的X轴上显示时间值时遇到问题

使用SQL数据库中的现有列派生或修改几个列

改进的SQL子字符串提取

如何根据几个条件 Select 值:如果满足一个范围的SUM,则对另一个范围求和

除了风格之外,还有什么理由更喜欢简单的CASE WHEN而不是搜索呢?

DB2 SQL查询结果多余数据

如何将 START 和 END 日期之间的日期差异作为 SQL 中的单独列获取

有没有办法在雅典娜中将字符串转换为 int ?

MS ACCESS 错误插入 X(...) 从 A 联合 Select ... 从 B

HIVE SQL where 子句未按预期工作

PostgreSQL:通过数组的元素从另一个表中 Select 数据,然后按顺序显示

如何使用 pg-promise 创建要在复杂的 sql 查询中使用的 VALUES 列表?

使用 json_agg 从 SQL 查询获取 [null] 响应