我的資料庫中有一個帶有 json 結構的文本列。Postgres v.10
它可能是這樣的:
{"pe_cd":"07","me_cd":"006","mf":"4.0","mfm":"4.0","pot":null,"earliestDate":[{"date":"2019-07-01","_destroy":false},{"date":"2020-01-01","_destroy":""}],"earliestDate2":null,"leavingDate":null}
如果earlyDate2 = null 那么我需要進行更新查詢并用earlyDate[] 中的第一個日期填充它。在這種情況下 2019-07-01
在這種情況下,目標應該是:
{"pe_cd":"07","me_cd":"006","mf":"4.0","mfm":"4.0","pot":null,"earliestDate":[{"date":"2019-07-01","_destroy":false},{"date":"2020-01-01","_destroy":""}],"earliestDate2":"2019-07-01","leavingDate":null}
我該如何撰寫此更新查詢?
小提琴
uj5u.com熱心網友回復:
要查詢您的 json 型別字串,您可以這樣做:
`SELECT * FROM yourtable
WHERE json_like_column::JSON->'earliestDate' IS NULL
`
:: 將您的字串轉換為 JSON 并且 -> 將從您的 json 中獲取 'eraliestDate' 欄位。您還可以使用 ->> 將該欄位的值轉換為字串。
uj5u.com熱心網友回復:
這是我為你想出的:
WITH null_dates AS
( -- Find the records with a NULL earliestDate2 and expand the dates stored
SELECT id, (jsonb_array_elements(attr->'earliestDate')->>'date')::DATE as d
FROM test
WHERE attr->>'earliestDate2' IS NULL
)
UPDATE test t
SET attr = attr||jsonb_build_object('earliestDate2', sub.edate)
FROM
( -- Get the min date per ID from CTE (null_dates)
SELECT id
, MIN(d) AS edate
FROM null_dates
GROUP BY id
) sub
WHERE t.id = sub.id
;
這里有一個小提琴來展示它的實際效果。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/370118.html
標籤:数组 json 细绳 PostgreSQL的
