我在 WITH 语句中做了很多查询。他们应该在一个事务中。我应该在事务中显式地覆盖我的大查询还是没有必要?
这是我的查询的粗略示例:
WITH
remains_actual AS (
SELECT
...
)
affected_remains AS (
INSERT INTO
...
ON CONFLICT (...) DO UPDATE SET
...
RETURNING
...
)
affected_products AS (
SELECT DISTINCT
...
)
INSERT INTO
....
最佳答案
来自docs :
PostgreSQL actually treats every SQL statement as being executed within a transaction. If you do not issue a BEGIN command, then each individual statement has an implicit BEGIN and (if successful) COMMIT wrapped around it.
WITH
语句仍算作单个语句,因此它将在隐式事务 block 中运行。
您可以使用一些返回当前事务 ID 的 CTE 自行测试:
with
tx1 as (select txid_current()),
tx2 as (select txid_current())
select * from tx1, tx2;
txid_current | txid_current
--------------+--------------
12814 | 12814
(1 row)
关于postgresql - WITH 语句中的查询是否在 PostgreSQL 的单个事务中执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56932562/