如何计算postgresql中json数组中的所有键

时间:2018-04-15 17:27:19

标签: json postgresql

我有一张表,其中我有表单ID和表单字段列

=======================
form_id | form_fields
=======================
  1     | [abc,def]

现在还有一个表包含提交表单的响应数据,如

================================
device_id | form_id | response
================================
  101     |    1    | {abc:true}
================================
  102     |    1    | {def:true}
================================
  103     |    1    | {def:true}
================================
  101     |    2    | {xyz :true}

我希望从第二个表中获得第一个表中form_fields form_id 1的数组值的所有计数。我的意思是结果就像

{abc:1,def:2}

一种方法是在所有响应中生成一个简单的json,然后逐个迭代json对象并检查值。有没有其他有效和更好的方法来解决这个问题?我是postgres的新手,所以如果这个问题太基础,请忽略。

谢谢!

1 个答案:

答案 0 :(得分:1)

我对此{abc:true}不太确定,因为我只处理列中的值,而不是key_value对,所以如果我错了,请纠正我

但如果它们也只是值(如varchar / ...),这应该可以正常工作

select count(*) from your_table where form_id = 1 and response = 'abc'

select count(*) from your_table where form_id = 1 and response = 'def'