UPDATE 和 return 某些行两次

UPDATE and return some rows twice

我尝试更新 return 行。问题是我使用嵌套的 select 和 UNION 来获取一些行两次,我想让它们 returned 两次。示例:

Table:

First_name | last_name | ready
-----------+-----------+------
john       | doe       | false
           | smith     | false
jane       |           | false

查询:

With list(name) as (
    Select First_name 
    from table1 
    where First_name Not null and ready=false
    union
    Select last_name 
    from table1 
    where last_name Not null and ready=false
)
Select * from list

这个returns:

John
jane
doe
smith

现在我想更新 select 找到的行并改用 update ... returning。但是 update 仅 return 受影响的三个行,而我希望它像示例中的 select 那样 return 行。有什么办法吗?

with list(name) as (
    select first_name 
    from table1 
    where first_name is not null and ready=false
    union all
    select last_name 
    from table1 
    where last_name is not null and ready=false
), u as (
    update table1
    set ready = true
    where
        (first_name is not null or last_name is not null)
        and
        not ready
)
select * from list

您需要 union all 才能拥有四行。这是is [not] null

重写为:

WITH cte AS (
   UPDATE table1
   SET    ready = true
   WHERE (first_name IS NOT NULL OR last_name IS NOT NULL)
   AND    NOT ready
   RETURNING first_name, last_name
   )
SELECT first_name FROM cte WHERE first_name IS NOT NULL
UNION ALL
SELECT last_name  FROM cte WHERE last_name IS NOT NULL;

相同的结果,只是更短更快:此查询访问 table1 一次,而不是像原来那样访问三次。
(在 table 测试中验证 EXPLAIN ANALYZE 的卓越性能。)

UNION ALL like @Clodoaldo already mentionedUNION 会消除重复项,这要慢得多(这里可能是错误的)。