实现说明
实际执行的是 SELECT / INSERT / CREATE——order_docs 是涉及的对象。
order_docs 是文件自己造的会话级临时表——库里不会有残留,会话终结即被清理。
用到的 SQL 构件:ORDER BY 固定了输出顺序;RETURNING 把受影响的行交回调用方;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY;补齐缺省列的 DEFAULT 值。
常见问题
这段 SQL 涉及哪些关系?
引用的是 order_docs。
核心语句
INSERT INTO order_docs VALUES
(1, '{"total": "49.50", "items": [{"sku": "A1", "qty": 3}, {"sku": "B2", "qty": 1}]}'),
(2, '{"items": [{"sku": "C3", "qty": 1}]}'),
(3, '{"total": [1, 2], "items": []}');
CREATE TEMP TABLE order_docs (
id integer PRIMARY KEY,
doc jsonb NOT NULL
);
代码示例
CREATE TEMP TABLE order_docs (
id integer PRIMARY KEY,
doc jsonb NOT NULL
);
INSERT INTO order_docs VALUES
(1, '{"total": "49.50", "items": [{"sku": "A1", "qty": 3}, {"sku": "B2", "qty": 1}]}'),
(2, '{"items": [{"sku": "C3", "qty": 1}]}'),
(3, '{"total": [1, 2], "items": []}');
-- PostgreSQL 17 SQL/JSON query functions with typed RETURNING and fallback clauses
SELECT
id,
JSON_EXISTS(doc, '$.items[*] ? (@.qty >= $min)' PASSING 3 AS min) AS has_bulk,
JSON_VALUE(
doc, '$.total'
RETURNING numeric
DEFAULT 0 ON EMPTY
DEFAULT -1 ON ERROR
) AS parsed_total,
JSON_QUERY(
doc, '$.items[*].sku'
WITH UNCONDITIONAL ARRAY WRAPPER
EMPTY ARRAY ON EMPTY
) AS sku_list
FROM order_docs
ORDER BY id;