且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Postgres中查询JSON

更新时间:2023-02-26 11:16:55

You're right, that's a problem with SQL syntax. Correct you query:

select * from json_test where content->'playersContainer'->'series' @> '[{"id":"1"}]';

Full example:

CREATE TABLE json_test (
  content jsonb
);

insert into json_test(content) VALUES ('{"id": "1",
    "team": {
      "id": "123",
      "name": "Shire Soldiers"
    },
    "playersContainer": {
      "series": [
        {
          "id": "1",
          "name": "Nick",
          "teamName": "Shire Soldiers",
          "ratings": [
            1,
            5,
            6,
            9
          ],
          "assists": 17,
          "manOfTheMatches": 20,
          "cleanSheets": 1,
          "data": [
            3,
            2,
            3,
            5,
            6
          ],
          "totalGoals": 19
        },
        {
          "id": "2",
          "name": "Pasty",
          "teamName": "Shire Soldiers",
          "ratings": [
            6,
            8,
            9,
            10
          ],
          "assists": 25,
          "manOfTheMatches": 32,
          "cleanSheets": 2,
          "data": [
            3,
            5,
            7,
            9,
            10
          ],
          "totalGoals": 24
        }
      ]
    }}');

select * from json_test where content->'playersContainer'->'series' @> '[{"id":"1"}]';

About @> operator. This question might be also useful.