2016-07-26 67 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]'