简体   繁体   中英

Postgres SQL: How to query jsonb column having data in array

I have a table customrule with a structure

id.       - int
name      - varchar
actions.  - jsonb

I already have read about the -> operator. But it seems not working in my case as I have data stored in as an array.

+-----------------------------------------------------------------------------------+
| Name | Id | Actions                                                               |
+-----------------------------------------------------------------------------------+
| CR-1 | 1  | [{"name": "Action1", "count": "1"},{"name": "Action2", "count": "2"}] |
+-------------------+---------------------------------------------------------------+
| CR-2 | 2  | [{"name": "Action5", "count": "1"},{"name": "Action4", "count": "2"}] |
+-----------------------------------------------------------------------------------+
| CR-3 | 3  | [{"name": "Action1", "count": "1"},{"name": "Action1", "count": "2"}] |
+-----------------------------------------------------------------------------------+

I want to query this data and get all records which have Action1 used in the actions column. Which should return row 1 and 3rd as a result.

You need to use the contains operator with an array parameter

select id, name, actions
from customrule 
where actions @> '[{"name": "Action1"}]'

Online example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM