Postgres,通过排序从 jsonb 数组更新语句
Postgres, update statement from jsonb array with sorting
我的 table 中有一个 jsonb 列 - 它包含 json 个对象的数组
这些对象中的字段之一是日期。
现在我在时间戳类型的 table 中添加了新列。
现在我需要一个语句,它可以让我用同一记录的 jsonb 数组列中的最新日期值更新新列。
以下语句非常适合从特定记录的 jsonb 数组列中选择最近日期:
select history.date
from document,
jsonb_to_recordset(document.history) as history(date date)
where document.id = 'd093d6b0-702f-11eb-9439-0242ac130002'
order by history.date desc
limit 1;
关于更新,我尝试了以下操作:
update document
set status_recent_change_date = subquery.history.date
from (
select id, history.date
from document,
jsonb_to_recordset(document.history) as history(date date)
) as subquery
where document.id = subquery.id
order by history.date desc
limit 1;
最后一条语句无效。
您很可能不需要使用 LIMIT
命令。
在SUBQUERY
:
里面做排序就够了
UPDATE document SET status_recent_change_date = subquery.hdate
FROM (
SELECT id, history.date AS hdate
FROM document, jsonb_to_recordset(document.history) AS history(date date)
ORDER BY history.date DESC
) AS subquery
WHERE document.id = subquery.id
UPDATE document d
SET status_recent_change_date = s.date
FROM (
SELECT DISTINCT ON (id)
*
FROM document,
jsonb_to_recordset(document.history) AS history(date date)
ORDER BY id, history.date DESC
) s
WHERE d.id = s.id;
使用 LIMIT
将不起作用,因为您限制了 SELECT
语句的整个输出。但是你想限制每个 document.id 的输出。这可以使用 DISTINCT ON (id)
.
来完成
此结果可用于使用 id
值更新每条记录。
我的 table 中有一个 jsonb 列 - 它包含 json 个对象的数组 这些对象中的字段之一是日期。 现在我在时间戳类型的 table 中添加了新列。 现在我需要一个语句,它可以让我用同一记录的 jsonb 数组列中的最新日期值更新新列。
以下语句非常适合从特定记录的 jsonb 数组列中选择最近日期:
select history.date
from document,
jsonb_to_recordset(document.history) as history(date date)
where document.id = 'd093d6b0-702f-11eb-9439-0242ac130002'
order by history.date desc
limit 1;
关于更新,我尝试了以下操作:
update document
set status_recent_change_date = subquery.history.date
from (
select id, history.date
from document,
jsonb_to_recordset(document.history) as history(date date)
) as subquery
where document.id = subquery.id
order by history.date desc
limit 1;
最后一条语句无效。
您很可能不需要使用 LIMIT
命令。
在SUBQUERY
:
UPDATE document SET status_recent_change_date = subquery.hdate
FROM (
SELECT id, history.date AS hdate
FROM document, jsonb_to_recordset(document.history) AS history(date date)
ORDER BY history.date DESC
) AS subquery
WHERE document.id = subquery.id
UPDATE document d
SET status_recent_change_date = s.date
FROM (
SELECT DISTINCT ON (id)
*
FROM document,
jsonb_to_recordset(document.history) AS history(date date)
ORDER BY id, history.date DESC
) s
WHERE d.id = s.id;
使用 LIMIT
将不起作用,因为您限制了 SELECT
语句的整个输出。但是你想限制每个 document.id 的输出。这可以使用 DISTINCT ON (id)
.
此结果可用于使用 id
值更新每条记录。