【问题标题】:PostgreSQL - Does a 'RETURNING ELSE' statement exist for an UPDATE?PostgreSQL - 更新是否存在“返回其他”语句?
【发布时间】:2021-11-25 02:27:25
【问题描述】:

我有这个问题:

update client
set start_date = current_date,
email = '123@fakeemail.com'
where client_id = 1
returning client_id, username, 1 as isSuccess

更新成功后返回如下:

client_id username isSuccess
1 test_name 1

更新不执行时,返回client_id、username和isSuccess,但它们的值为空。

我遇到的问题是自定义不执行更新时返回的内容。如果没有执行更新,我需要返回以下内容:

client_id username isSuccess
NULL NULL 0

在不执行更新时,编写带有 ELSE 子句的 RETURNING 子句以获取上述结果集有什么技巧吗?或者还有其他方法可以获得我需要的结果集吗?以下代码不起作用 -

 update client
    set start_date = current_date,
    email = '123@fakeemail.com'
    where client_id = 1
    returning client_id, username, 1 as isSuccess
else client_id is null, username is null, 0 as isSuccess

【问题讨论】:

  • 根据 PostgreSQL 文档“可选的 RETURNING 子句导致 UPDATE 根据实际更新的每一行计算和返回值。”如果没有行,那么它将仅返回 null。

标签: sql postgresql sql-update


【解决方案1】:

RETURNING 子句中没有ELSE 语句,但您可以执行类似的操作。基本思想是从您的更新中获取结果,使用 UNION 将其与另一行组合并返回第一个结果。

Postgres 不允许我们使用带有 UNION 的更新语句,因此我们必须将更新语句放在 CTE 中:

WITH client_update AS (
  update client
  set start_date = current_date,
  email = '123@fakeemail.com'
  WHERE client_id = 2
  returning client_id, username, 1 as isSuccess, 1 as result_order
)
SELECT client_id, username, isSuccess FROM
  (
    SELECT client_id, username, isSuccess, result_order
    FROM client_update
    UNION ALL
    SELECT null, null, 0, 2
  ) sub 
ORDER BY result_order 
LIMIT 1;

我添加了一个附加列,result_order,因此我们可以手动指定首选的结果。在这种情况下,如果返回子句返回一个结果,我们想返回那个结果,所以它得到 1。

【讨论】:

  • 太棒了,这就像一个魅力。非常感谢!!
猜你喜欢
  • 1970-01-01
  • 2018-02-08
  • 1970-01-01
  • 2012-11-03
  • 1970-01-01
  • 1970-01-01
  • 2020-07-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多