gpt4 book ai didi

SQL 更新标量函数

转载 作者:行者123 更新时间:2023-11-29 12:05:33 25 4
gpt4 key购买 nike

当我运行这个查询时:

UPDATE myTable SET x = (SELECT round(random()*100));

所有记录都具有相同的 x 值。这是有道理的。

当我运行这个查询时:

UPDATE myTable SET x = round(random()*100);

它更新表中的所有记录,并且对于每条记录,x 的值都不同。

我想知道第二个查询的后台发生了什么。它是否为每个记录 id(1....n) 运行更新查询?

我猜它的工作方式类似于触发器,其中在更新之前对每一行

  1. 触发器拦截
  2. 调用函数并设置x的值
  3. 执行查询

实际发生了什么?

最佳答案

其实很简单。函数 random() 被定义为 VOLATILE

如果将其放入子查询中,则会生成一个只有一行的派生表。 Postgres 可以具体化结果并在外部查询中多次重复使用它。

否则 Postgres 会为每一行调用该函数。这就是必须处理 VOLATILE 函数的方式。 Per documentation on function volatility :

A VOLATILE function can do anything, including modifying the database. It can return different results on successive calls with the same arguments. The optimizer makes no assumptions about the behavior of such functions. A query using a volatile function will re-evaluate the function at every row where its value is needed.

大胆强调我的。

关于SQL 更新标量函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22488783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com