Postgresql Postgres,使用排序从jsonb数组更新语句

Postgresql Postgres,使用排序从jsonb数组更新语句,postgresql,sql-update,jsonb,Postgresql,Sql Update,Jsonb,我的表中有一个jsonb列——它包含json对象数组 这些对象中的一个字段是日期。 现在,我在timestamp类型的表中添加了新列。 现在我需要一条语句,它可以帮助我用jsonb数组列中同一记录的最新日期值更新新列 下面的语句非常适合从特定记录的jsonb数组列中选择最近日期: select history.date from document, jsonb_to_recordset(document.history) as history(date date) where

我的表中有一个jsonb列——它包含json对象数组 这些对象中的一个字段是日期。 现在,我在timestamp类型的表中添加了新列。 现在我需要一条语句,它可以帮助我用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
命令

子查询中进行排序就足够了:

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

您很可能不需要使用
LIMIT
命令

子查询中进行排序就足够了:

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

使用
LIMIT
将不起作用,因为您限制了
SELECT
语句的整个输出。但您希望限制每个document.id的输出。这可以使用
DISTINCT ON(id)
完成

此结果可用于使用每个记录的
id
值更新记录。

使用
LIMIT
将不起作用,因为您限制了
SELECT
语句的整个输出。但您希望限制每个document.id的输出。这可以使用
DISTINCT ON(id)
完成


此结果可用于使用每个记录的
id
值来更新每个记录。

更新既不支持
order by
也不支持
limit
-如果确实要将其限制为一行,您需要将其移动到子查询更新中,该子查询更新既不支持
order by
也不支持
limit
——如果您真的想将其限制为一行,则需要将其移动到子查询错误:“status_history”表中,该表不在语句中错误:СбБББАА:бббббб尝试为history.date添加别名。我编辑过queryYes,应该有用吧?但我使用了@S-Man的例子。非常感谢)错误:“status_history”表在语句中缺失错误:СбББА:Сбббббббббббббббббб1073。我编辑过queryYes,应该有用吧?但我使用了@S-Man的例子。(无论如何,非常感谢)