处理数组和 none 数组条目的 Postgres JSONB 列 select 语句
Postgres JSONB column select statement that handles array and none array entries
我有一个带有电子邮件 table 的 postgres 数据库,其中有一个 jsonb 列用于存储电子邮件发送给谁。如果一封电子邮件被发送给一个人,它会被存储为
{"name": "bob", "email": "bob@email.com"}
我可以通过
查询
select * from email where (to->>'address') = 'bob@email.com';
如果电子邮件被发送给多个人,它的存储方式如下:
[{"email": "bob@email.com"}, {"email": "dave@email.com"}]
我可以这样查询:
select * from email where to @> '[{"email": "bob@email.com"}]';
我想知道是否有人对可以 return 两种情况的结果的单个查询有任何想法。
你可以使用 jsonb_typeof()
:
select *
from email
where
(jsonb_typeof(to) = 'object' and to->>'address' = 'bob@email.com')
or (jsonb_typeof(to) = 'array' and to @> '[{"email": "bob@email.com"}]')
我有一个带有电子邮件 table 的 postgres 数据库,其中有一个 jsonb 列用于存储电子邮件发送给谁。如果一封电子邮件被发送给一个人,它会被存储为
{"name": "bob", "email": "bob@email.com"}
我可以通过
查询select * from email where (to->>'address') = 'bob@email.com';
如果电子邮件被发送给多个人,它的存储方式如下:
[{"email": "bob@email.com"}, {"email": "dave@email.com"}]
我可以这样查询:
select * from email where to @> '[{"email": "bob@email.com"}]';
我想知道是否有人对可以 return 两种情况的结果的单个查询有任何想法。
你可以使用 jsonb_typeof()
:
select *
from email
where
(jsonb_typeof(to) = 'object' and to->>'address' = 'bob@email.com')
or (jsonb_typeof(to) = 'array' and to @> '[{"email": "bob@email.com"}]')