从基于json的表中获取数据

时间:2018-08-07 00:03:54

标签: postgresql

我有一个表,其中的列“ sample_column”为jsonb。

谁能告诉我如何基于Postgresql中的'sample_column'选择数据?

sample_column中的数据示例:{“ a”:[]}
                                     {“ a”:[1,2,3]}

如果sample_column的值为{“ a”:[]},我想获取所有数据

这是我所做的:Select * from sample_table where sample_column = '{"a": []}'

我收到错误消息:json类型的输入语法无效。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

如果a键是区分符,则应执行以下操作:

select * from sample_table where sample_column->'a' = '[]';

如果要处理更多键,则可能需要使用ANDOR运算符,具体取决于您要执行的操作。以下是说明:

-- Create table and insert some rows in it
create table sample_table (sample_column jsonb);
insert into sample_table values ('{"a": []}'), ('{"b": 2, "a": [2,3]}'), ('{"c": 20}');

-- Use an OR operator to get rows where the value for the "b" key is greater 1
-- or the value for the "c" key is equal to 20.
select * from sample_table where sample_column->'b' > '1' or sample_column->'c' = '20';

您应该得到类似的东西:

 {"a": [2, 3], "b": 2}
 {"c": 20}

要获取sample_column的所有数据,其值不是{“ a”:[]},可以执行以下操作:

select * from sample_table where sample_column != '{"a": []}'::jsonb;

在这里,添加的::jsonb将字符转换为jsonb类型,这应该使比较成为可能。

我希望这证明是有用的。

相关问题