我如何 select "occupation"?

How do I just select the "occupation"?

我有以下内容:

SELECT * 
FROM (
   SELECT '{"people": [{"name": "Bob", "occupation": "janitor"}, {"name": "Susan", "occupation": "CEO"}]}'::jsonb as data
) as b 
WHERE data->'people' @> '[{"name":"Bob"}]'::jsonb;

我正在筛选对象 '{"name": "Bob", "occupation": "janitor"}'

如何return鲍勃的职业("janitor")?

SELECT data->'people'->>'occupation'  
FROM (
   SELECT '{"people": [{"name": "Bob", "occupation": "janitor"}, {"name": "Susan", "occupation": "CEO"}]}'::jsonb as data
) as b 
WHERE data->'people' @> '[{"name":"Bob"}]'::jsonb;

returns

?column?
--------
NULL

寻找:

occupation
----------
janitor

如果您不关心 jsonb 所在行的任何其他内容,您可以将所有元素从 jsonb 中取出,然后将它们用作单独的元素 select from

SELECT data->>'occupation' as occupation
FROM (
  SELECT jsonb_array_elements(
    '{"people": 
       [
         {"name": "Bob", "occupation": "janitor"}, 
         {"name": "Susan", "occupation": "CEO"}
       ]
     }'::jsonb->'people') as data) as b
WHERE data @> '{"name":"Bob"}';

结果

occupation
-----------
janitor
(1 row)

您的 "people" 元素是一个数组。您可以使用 jsonb_array_elements 函数获取数组的元素。之后,您可以过滤 person->>'name':

SELECT  person->>'occupation' as occupation
FROM    (
        SELECT  person.value as person
        FROM    (
                SELECT     
                  '{"people": 
                     [
                       {"name": "Bob", "occupation": "janitor"}, 
                       {"name": "Susan", "occupation": "CEO"}
                     ]
                   }'::jsonb as data
                ) a
        CROSS JOIN
                jsonb_array_elements(data->'people') as person
        ) b
WHERE   person->>'name' = 'Bob';

注意->>returns文字,而->returnsjsonb.