Postgres 查询以返回其中 json 列中的 json 包含多个数组元素的行



我们正在使用Postgres DB,因为我们有一个表包含JSON类型的列,格式如下

{
  "name" : "XXX",
  "id"  : "123",
  "course" :[
     {
       "name" : "java",
       "tutor":"YYYY"
     },
     {
       "name" : "python",
       "tutor":"ZZZZ"
     }
   ]  
}

{
  "name" : "XXX",
  "id"  : "123",
  "course" :[
     {
       "name" : "java",
       "tutor":"YYYY"
     },
     {
       "name" : "python",
       "tutor":"ZZZZ"
     }
   ]  
}

例如,我们有两行,在 JSON 列中,我们每行都像上面一样

我想 Postgre 查询 ,它将检查课程数组中的元素数量,如果它不止一个,则只返回该行

我不知道如何从 JSON 键内部计算数组元素

可以任何建议

为什么不直接json_array_length ?..例如:

f=# with c(j) as (values('{
  "name" : "XXX",
  "id"  : "123",
  "course" :[
     {
       "name" : "java",
       "tutor":"YYYY"
     },
     {
       "name" : "python",
       "tutor":"ZZZZ"
     }
   ]
}'::json))
select json_array_length(j->'course') from c;
 json_array_length
-------------------
                 2
(1 row)

所以喜欢

select * from table_name where json_array_length(j->'course') > 1

最新更新