PostgreSQL:在填充为 json 数组的 JSONB 列中按 json 属性 搜索

PostgreSQL: Search by json property in JSONB column that is populated as json array

所以我有这个:

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": "hello@example.com"
  }
]'::JSONB)

我需要获取 event.id 列表,其中 'hello@example.com' 在 "email" 字段中至少在发言人 JSONB 列中出现一次 .

我试过:

select id from events where events.speakers->'email' ? '"hello@example.com"';
<no results>

以及许多其他从未奏效的片段。我不认为这是一种不寻常的使用模式!

你必须先用jsonb_array_elements

扩展数组
SELECT * FROM (
   select id, jsonb_array_elements(speakers) as event from events
) as a where event->'email' ? 'hello@example.com'