更新并返回一些行两次

时间:2015-02-14 15:48:44

标签: sql postgresql sql-update union common-table-expression

我尝试更新并返回行。问题是我使用UNION的嵌套选择来获取两次行,我想让它们返回两次。例如:

表:

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

返回:

John
jane
doe
smith

现在,我想要更新select找到的行,然后使用update ... returning。但是update只返回三个受影响的行,而我希望它返回行,就像示例中的select一样。有什么办法吗?

2 个答案:

答案 0 :(得分:1)

重写为:

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而不是原始的三次。
(在测试表上验证EXPLAIN ANALYZE的卓越性能。)

UNION ALL,如@Clodoaldo already mentionedUNION将消除重复,这种重复速度要慢得多(这里可能有误)。

答案 1 :(得分:0)

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