在 PostgreSQL-11 中有条件地更新字段时出错
Error updating field conditionally in PostgreSQL-11
给定以下查询:
insert into shopify_app_shops as s
(
myshopify_name,
hostname,
user_status,
offline_access_token,
offline_access_token_updated_at,
updated_at
)
values
(
%(myshopify_name)s,
%(hostname)s,
%(user_status)s,
%(offline_access_token)s,
now(),
now()
)
on conflict (myshopify_name)
do update
set
hostname=%(hostname)s,
user_status=%(user_status)s,
offline_access_token_updated_at =
CASE
WHEN offline_access_token == %(offline_access_token)s
THEN offline_access_token_updated_at
ELSE now()
END,
offline_access_token=%(offline_access_token)s,
updated_at = now()
returning myshopify_name
;
我收到错误:
Failed with: column reference "offline_access_token" is ambiguous LINE 28: WHEN offline_access_token == NULL
但是,如果我通过在 table 名称前加上这样的名称来完全指定字段:
WHEN shopify_app_shops.offline_access_token == %(offline_access_token)s
我反而得到这个错误:
Failed with: invalid reference to FROM-clause entry for table "shopify_app_shops" LINE 28: WHEN
shopify_app_shops.offline_access_token == NULL
此时我不知所措!
documentation for postgresql-11 update statements 明确指出用于设置值的表达式可以包含对其他字段的引用以访问旧值:
expression
An expression to assign to the column. The expression can use the old values of this and other columns in the table.
那我做错了什么?
使用 table 别名
WHEN s.offline_access_token ...
使用别名时,table 名称不可见。不相关,您可能应该使用 IS NOT DISTINCT FROM
而不是 ==
。
给定以下查询:
insert into shopify_app_shops as s
(
myshopify_name,
hostname,
user_status,
offline_access_token,
offline_access_token_updated_at,
updated_at
)
values
(
%(myshopify_name)s,
%(hostname)s,
%(user_status)s,
%(offline_access_token)s,
now(),
now()
)
on conflict (myshopify_name)
do update
set
hostname=%(hostname)s,
user_status=%(user_status)s,
offline_access_token_updated_at =
CASE
WHEN offline_access_token == %(offline_access_token)s
THEN offline_access_token_updated_at
ELSE now()
END,
offline_access_token=%(offline_access_token)s,
updated_at = now()
returning myshopify_name
;
我收到错误:
Failed with: column reference "offline_access_token" is ambiguous LINE 28: WHEN offline_access_token == NULL
但是,如果我通过在 table 名称前加上这样的名称来完全指定字段:
WHEN shopify_app_shops.offline_access_token == %(offline_access_token)s
我反而得到这个错误:
Failed with: invalid reference to FROM-clause entry for table "shopify_app_shops" LINE 28: WHEN shopify_app_shops.offline_access_token == NULL
此时我不知所措!
documentation for postgresql-11 update statements 明确指出用于设置值的表达式可以包含对其他字段的引用以访问旧值:
expression
An expression to assign to the column. The expression can use the old values of this and other columns in the table.
那我做错了什么?
使用 table 别名
WHEN s.offline_access_token ...
使用别名时,table 名称不可见。不相关,您可能应该使用 IS NOT DISTINCT FROM
而不是 ==
。