我尝试更新并返回行。问题是我使用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
一样。有什么办法吗?
答案 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 mentioned。 UNION
将消除重复,这种重复速度要慢得多(这里可能有误)。
答案 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