在postgres中使用JSON,如何查询嵌套数组?

时间:2017-12-06 12:32:40

标签: ruby-on-rails json postgresql

我有一些带有User json列的details条记录,如下所示:

User.create(details: {accounts: [{name: 'one', id: 1}, {name: 'two', id: 2}])
User.create(details: {accounts: [{name: 'three', id: 3}, {name: 'two', id: 2}])
User.create(details: {accounts: [{name: 'three', id: 3}, {name: 'four', id: 4}])

如何查询id2的所有记录?

1 个答案:

答案 0 :(得分:0)

感谢Using jsonb (PostgreSQL), how do I retrieve items with a certain value that's saved as an array?我被放在了正确的轨道上。

要匹配的查询:

User.where("? in (SELECT json_array_elements(details->'accounts')->>'id')", "2")