获取实际更新为不同值的列?

Get the columns that were actually updated to a different value?

我运行是这样的:

cursor.execute(
    '''
    UPDATE my_table
    SET name=%s, about=%s, title=%s
    WHERE id=%s
    ''',
    (name, about, title, id_)
)

保证只更新一行,因为它是根据 id 主键进行更新。

然而,大多数时候只有一个字段实际上发生变化,即abouttitle是"updated"到它们已经是相同的值,实际上只有 name 发生了变化。

我怎样才能知道哪些列实际发生了变化?这需要记录每个单独的更改。

您可以 select 更新前的值并使用 RETURNING * 比较最终查询中的值,如下所示:

t=# create table m1 (i int, e int);
CREATE TABLE
Time: 1.855 ms
t=# insert into m1 select 1,2;
INSERT 0 1
Time: 1.037 ms
t=# begin;
BEGIN
t=# with o as (select * from m1 where i=1)
,u as (update m1 set e=3 where i=1 returning *)
select * from o
join u on o.i = u.i
;
 i | e | i | e
---+---+---+---
 1 | 2 | 1 | 3
(1 row)

所以你可以把逻辑放在反对 u.e <> o.e 或类似的地方