我如何选择“职业”?

时间:2015-06-07 18:19:04

标签: postgresql postgresql-9.4 jsonb

我有以下内容:

Mat flooded=new Mat();
Point flood=new Point(1,1);
// floodedmat = Mat.zeros(myMat2.size(), CvType.CV_8UC1);
Imgproc.floodFill(myMat2, flooded, flood, new Scalar(255, 255, 255));
Utils.matToBitmap(flooded, copy);

我正在过滤对象'{“name”:“Bob”,“Occup”:“janitor”}'

我如何归还鲍勃的职业(“看门人”)?

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

返回

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;

寻找:

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

2 个答案:

答案 0 :(得分:1)

如果你不关心jsonb所在的行上的任何其他内容,你可以从jsonb中取出所有元素,然后将它们作为单独的元素来选择

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"}';

结果

  

职业
  -----------
   看门
  (1排)

答案 1 :(得分:0)

您的“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';

请注意,->>会返回文字,而->会返回jsonb