[英]Postgres compare multiple jsonb fields
我在表中有一個jsonb“聯系人”字段,該字段是:
例:
{
"main": [{
"name": "Bobby Smith",
"email": "bs@example.com",
"telephone": "555-999-0000"
}, {
"name": "Joan Smith",
"email": "js@example.com",
"telephone": "555-999-0002"
}],
"billing": [{
"name": null,
"region": "Arizona",
"address": ["PO BOX 123", "456 Nowhere Road"],
"country": "USA",
"locality": "BigMac",
"postalCode": "90210"
}],
"emergency": [{
"name": "John Cooper",
"email": "jc@example.com",
"telephone": "555-987-0000"
}]
}
我想有一種簡單的方法,可以對最外層對象中的鍵不可知的名稱字段以及每個數組中的元素數進行比較。
實際上,這是:SELECT * FROM client where where contact#>>'{*,*,name}'='John Cooper';
將返回包含上述內容的行,因為它與'{emergency,0,name}'相匹配
您需要展開當前數據庫設計的數據,例如:
select t.*
from t, jsonb_each(contacts) e, jsonb_array_elements(e.value) c
where c ->> 'name' = 'John Cooper'
但這不能為您的查詢使用任何索引。
更好的設計是僅將聯系數據存儲在聯接表的每一行上,例如:
t t_contact
------------------ -------------------------
t_id primary key t_id references t(t_id)
contact_type text
contact jsonb
然后,您可以索引t_contact(contact)
並進行查詢,例如:
select t.*
from t
join t_contact using (t_id)
where contact ->> 'name' = 'John Cooper'
group by t.t_id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.