2016-07-26 69 views
2

所以我有这样的:PostgreSQL的:通过填充作为JSON阵列中JSONB列JSON房产搜索

CREATE EXTENSION "uuid-ossp"; -- not related, just for the uuid_generate_v4 

CREATE TABLE events (
    id UUID PRIMARY KEY NOT NULL DEFAULT uuid_generate_v4(), 
    speakers JSONB NOT NULL DEFAULT '[]'::jsonb 
); 

INSERT INTO events (id, speakers) values (uuid_generate_v4(), '[ 
    { 
    "id": "de3ae2c7-19f6-4c69-81ae-467034c06101", 
    "email": "" 
    }, 
    { 
    "id": "c8cf8fe8-a6b7-4cbc-b2c7-729c6108ff5f", 
    "email": "[email protected]" 
    } 
]'::JSONB) 

我需要得到的event.id列表,其中“[email protected]”出现在在发言者JSONB列中至少一次“电子邮件”字段。

我想:

select id from events where events.speakers->'email' ? '"[email protected]"'; 
<no results> 

而且许多从来没有做过其他片段。我不认为这是一种不寻常的使用模式!

回答

1

你必须与第一展开数组jsonb_array_elements

SELECT * FROM (
    select id, jsonb_array_elements(speakers) as event from events 
) as a where event->'email' ? '[email protected]'