如何交换 PSQL 中 table 中特定列的两条记录?

How can I swap two records from particular column in a table in PSQL?

考虑一个 table 测试包含 id 和 name 属性。

那个值。

编号 |姓名

1 |拉吉

2 |库马尔

从上面的示例table,我只知道id,所以通过id我需要交换名字,如下所示,

编号 |姓名

1 |库马尔

2 |拉吉

我们可以使用 'With Query' 交换特定行中的两个值。 使用'with'我们可以拿回来用
解决需求的查询,

with backup1 as (select name from test where id = 2), backup2 as (update test set name = (select name from test where id = 1) where id = 2) update test set name = (select * from backup1) where id = 1;

在上面的查询中,备份1包含id为2的名称,之后使用更新查询我取了id为1的名称
存储在 id 为 2 的名称字段中。
然后再次使用更新查询我从备份中获取名称并将其存储在 id 为 1 的名称字段中,这样我们可以交换。

update test
    set name = case id
        when 1 then (select name from test where id = 2)
        when 2 then (select name from test where id = 1)
    end
where id in (1,2);