[英]with activerecord how can I select records based on the highest value of a field?
[英]How can I select records that match a value in a json field array?
我正在嘗試返回與數組元素匹配的記錄,該數組元素等於 json 字段中的特定值。
我找到了如何 select 所有包含來自 postgres json 字段的某些值的記錄,該字段包含一個接近我的問題的數組。 但是,我認為關鍵區別在於我使用 json 而不是 jsonb。 由於某些原因,我目前需要使用 json。 當我嘗試其他帖子中的步驟時,我收到與以下相同的錯誤。
我有這個示例data
{"name": "Bob", "scores": [64, 66]}
{"name": "Sally", "scores": [66, 65]}
{"name": "Kurt", "scores": [69, 71, 72, 67, 68]}
{"name": "Libby", "scores": [72, 73, 74, 75]}
{"name": "Frank", "scores": [80, 81, 82, 83]}
我正在嘗試運行此查詢:
SELECT data
FROM tests.results
where (data->>'scores') @> '[72]';
我期望結果中有兩行:
{"name": "Kurt", "scores": [69, 71, 72, 67, 68]}
{"name": "Libby", "scores": [72, 73, 74, 75]}
但我得到:
SQL Error [42883]: ERROR: operator does not exist: text @> integer
Hint: No operator matches the given name and argument type(s).
You might need to add explicit type casts.
我目前使用 Postgres 10,但可能會升級到 12。感謝任何幫助。
您需要使用->
而不是->>
。 前者返回一個json object,而后者返回文本; 同時, @>
運算符對 json 對象進行操作,而不是對文本進行操作。
SELECT data
FROM tests.results
where (data->'scores')::jsonb @> '[72]';
WITH results AS (
SELECT '{"name": "Bob", "scores": [64, 66]}'::json mydata
UNION ALL SELECT '{"name": "Sally", "scores": [66, 65]}'::json
UNION ALL SELECT '{"name": "Kurt", "scores": [69, 71, 72, 67, 68]}'::json
UNION ALL SELECT '{"name": "Libby", "scores": [72, 73, 74, 75]}'::json
UNION ALL SELECT '{"name": "Frank", "scores": [80, 81, 82, 83]}'::json
)
SELECT mydata::text
FROM results
where (mydata->'scores')::jsonb @> '[72]';
| mydata |
| ------------------------------------------------ |
| {"name": "Kurt", "scores": [69, 71, 72, 67, 68]} |
| {"name": "Libby", "scores": [72, 73, 74, 75]} |
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.