I have a table data_table like this
| id | reciever
| (bigint) |(jsonb)
----------------------------------------------------------------------
| 1 | [{"name":"ABC","email":"abc@gmail.com"},{"name":"ABDFC","email":"ab34c@gmail.com"},...]
| 2 | [{"name":"DEF","email":"deef@gmail.com"},{"name":"AFDBC","email":"a45bc@gmail.com"},...]
| 3 | [{"name":"GHI","email":"ghfi@gmail.com"},{"name":"AEEBC","email":"5gf@gmail.com"},...]
| 4 | [{"name":"LMN","email":"lfmn@gmail.com"},{"name":"EEABC","email":"gfg5@gmail.com"},...]
| 5 | [{"name":"PKL","email":"dfdf@gmail.com"},{"name":"ABREC","email":"a4rbc@gmail.com"},...]
| 6 | [{"name":"ANI","email":"fdffd@gmail.com"},{"name":"ABWC","email":"abrtc@gmail.com"},...]
when i run on pg admin it works fine
I want to fetch row by putting email in where condition like select * from data_table where receiver = 'abc@gmail.com'.
there can be more data in array so i have shown "...".
I have tried like where receiver-->>'email'='abc@gmail.com'
but it is working in the case {"name":"ABC","email":"abc@gmail.com"} only
not in array where i have to chaeck every email in array
Help will be appreciated.
One option is to use exists
and jsonb_array_elements()
:
select t.*
from mytable t
where exists (
select 1
from jsonb_array_elements(t.receiver) x(elt)
where x.elt ->> 'email' = 'abc@gmail.com'
)
This gives you all rows where at least one element in the array has the given email.
If you want to actually exhibit the matching elements, then you can use a lateral join
instead (if more than one element in the array has the given email, this duplicates the row):
select t.*, x.elt
from mytable t
cross join lateral jsonb_array_elements(t.receiver) x(elt)
where x.elt ->> email = 'abc@gmail.com'
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.