postgre使用postgres CTE从EXISTS查询中运行sql函数



在postgres sql函数中,我只想在CTE返回任何行时运行function_update。此查询适用于此。

with common_table as (select 1 where true) select function_update('value') from common_table

但是,如果我还想返回function_update是否更新了任何行,那么它就不起作用。函数确实正确地返回了truefalse,这取决于CTE是否返回了任何行,但function_update似乎没有运行。

with common_table as (select 1 where true) select exists(select function_update('value') from common_table)

function_updateupdate mytable set column1 = 'changed' where column2 = arg_value一样简单。当我运行上面的第一个查询而不是第二个查询时,mytable会得到更新。为什么这不起作用,我需要改变什么?

为什么这不能像预期的一样工作

Exists检查是否存在,查询优化器不必执行该函数。下面的例子表明,我们可以预期一个除以0的错误:

select 1 WHERE EXISTS (SELECT 1/0);
-- 1

db<>小提琴演示


我需要更改什么?

一种方法是强制物化:

select 1 WHERE EXISTS (WITH cte AS MATERIALIZED (SELECT 1/0) SELECT * FROM cte)
-- division by 0

db<>小提琴演示

最新更新