Psql查询json数组

时间:2014-11-27 10:28:22

标签: arrays json postgresql postgresql-9.3

我在postgres db中存储的json具有以下结构。我需要获取电子邮件所有域名为' gmail.com'

的行

ROW1:

{
   "student_id": "123",
   "name": "foo",
   "emails":[
      {
        "id": "777",
        "domain": "gmail.com"
      },
      {
        "id": "888",
        "domain": "gmail.com"
      }
   ]
} 

行2:

{
   "student_ id": "345",
   "name": "booo",
   "emails":[
      {
        "id": "444",
        "domain": "gmail.com"
      },
      {
        "id": "555",
        "domain": "yahoo.com"
      }
   ]
} 

在这种情况下,我的结果应该只是student_id 123的学生,即第1行。请帮助。

1 个答案:

答案 0 :(得分:0)

如果表名为student,则保存json数据的字段名称为data

WITH
  mail_domain AS (
    SELECT
      (data->'student_id')::text AS student_id,
      (JSON_ARRAY_ELEMENTS(data->'emails')->'domain')::text AS domain
    FROM
      student),

  selected_student AS (
    SELECT
      student_id
    FROM
      mail_domain
    WHERE
      domain = '"gmail.com"'

    EXCEPT

    SELECT
      student_id
    FROM
      mail_domain
    WHERE
      domain != '"gmail.com"')

SELECT
  *
FROM
  student
WHERE
  (data->'student_id')::text IN (
    SELECT
      student_id
    FROM
      selected_student);