Postgresql从JSON列中选择
假设我使用的是第9.3页,我有一个带有json列“meta_data”的post表: json列“元数据”的示例内容Postgresql从JSON列中选择,sql,json,postgresql,postgresql-9.3,Sql,Json,Postgresql,Postgresql 9.3,假设我使用的是第9.3页,我有一个带有json列“meta_data”的post表: json列“元数据”的示例内容 { "content": "this is a post body", "comments": [ { "user_id": 1, "content": "hello" }, { "user_id": 2, "content": "foo" }, { "user_id":
{
"content": "this is a post body",
"comments": [
{
"user_id": 1,
"content": "hello"
},
{
"user_id": 2,
"content": "foo"
},
{
"user_id": 3,
"content": "bar"
}
]
}
如何从元数据列的评论数组中找到用户id=1的所有帖子?我几乎肯定我没有正确地实现这一点,但请尝试一下
select *
from posts
where id in (
select id from (
select id,
json_array_elements(meta_data->'comments')->'user_id' as user_id
from posts
) x
where cast(user_id as varchar) = '1'
);
可能有一个像@>
这样的数组操作符,它将不再需要嵌套的select语句,但我现在似乎无法让它工作
让我知道这是否走上了正确的轨道,我相信如果需要,我们可以找到它。在我看来,这更适合传统的关系建模。Pg中有限的json支持并不意味着您应该在常规关系也可以使用json的情况下使用json。我应该提到的是,这个示例只是这个问题的一个过于简化的版本。实际上,JSON要复杂得多。您能否添加plv8扩展?