我有下表和设置
create table test (
id serial primary key,
name text not null,
meta json
);
insert into test (name, meta) values ('demo1', '{"name" : "Hello"}')
Run Code Online (Sandbox Code Playgroud)
但是,当我运行此查询时,这就是结果
select * from test;
id | name | meta
----+-------+--------------------
1 | demo1 | {"name" : "Hello"}
(1 row)
Run Code Online (Sandbox Code Playgroud)
但
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.
Run Code Online (Sandbox Code Playgroud)
-
select * from test where cast(meta->'name' as text) = 'Hello';
id | name | meta
----+------+------
(0 rows)
Run Code Online (Sandbox Code Playgroud)
这很有效
select * from test where cast(meta->'name' as text) = '"Hello"';
id | name | meta
----+-------+--------------------
1 | demo1 | {"name" : "Hello"}
(1 row)
Run Code Online (Sandbox Code Playgroud)
任何人都可以告诉我这个引用的相关性是什么以及它为什么不进行简单的字符串搜索/比较?或者,这与铸造有关吗?
那是因为->得到一个字段而不是一个值,所以你需要添加强制转换来对postgresql说你想要的数据类型.
所以要像你想要的那样运行你的查询你需要使用->>获取json元素的文本在文档JSON函数和操作符上看到它
所以你的查询应该是这样的:
select *
from test
where meta->>'name' = 'Hello';
Run Code Online (Sandbox Code Playgroud)
看到它在这里工作:http://sqlfiddle.com/#!15/bf866/8