Postgres json选择不忽略引号

时间:2015-10-12 01:39:38

标签: postgresql

我有以下表格和设置

create table test (
  id serial primary key,
  name text not null,
  meta json
);

insert into test (name, meta) values ('demo1', '{"name" : "Hello"}')

但是,当我运行此查询时,这就是结果

select * from test;
 id | name  |        meta
----+-------+--------------------
  1 | demo1 | {"name" : "Hello"}
(1 row)

但是

select * from test where meta->'name' = 'Hello';
ERROR:  operator does not exist: json = unknown
LINE 1: select * from test where meta->'name' = 'Hello';
                                              ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

-

select * from test where cast(meta->'name' as text) = 'Hello';
 id | name | meta
----+------+------
(0 rows)

这是有效的

select * from test where cast(meta->'name' as text) = '"Hello"';
 id | name  |        meta
----+-------+--------------------
  1 | demo1 | {"name" : "Hello"}
(1 row)

有谁能告诉我这句话的相关性是什么以及为什么它不进行简单的字符串搜索/比较?或者,这是否与铸造有关?

1 个答案:

答案 0 :(得分:6)

那是因为new得到的字段不是值,所以你需要添加强制转换来对postgresql说你想要的数据类型。

因此,要运行您的查询,您需要使用->获取json元素作为文本,请在文档JSON Functions and Operators

上查看

所以你的查询应该是这样的:

->>

在此处查看:http://sqlfiddle.com/#!15/bf866/8