运算符不存在:json = json

Isa*_*aac 20 sql postgresql json jsonb postgresql-9.4

当我尝试从表中选择一些记录时

    SELECT * FROM movie_test WHERE tags = ('["dramatic","women", "political"]'::json)
Run Code Online (Sandbox Code Playgroud)

sql代码抛出错误

LINE 1: SELECT * FROM movie_test WHERE tags = ('["dramatic","women",...
                                        ^
HINT:  No operator matches the given name and argument type(s). You might      need to add explicit type casts.

********** ?? **********

ERROR: operator does not exist: json = json
SQL ??: 42883
????:No operator matches the given name and argument type(s). You might need to add explicit type casts.
??:37
Run Code Online (Sandbox Code Playgroud)

我错过了什么或者我可以在哪里了解这个错误.

kli*_*lin 25

您无法比较json值.您可以改为比较文本值:

SELECT * 
FROM movie_test 
WHERE tags::text = '["dramatic","women","political"]'
Run Code Online (Sandbox Code Playgroud)

但请注意,类型的值以json给定它们的格式存储为文本.因此,比较的结果取决于您是否始终如一地应用相同的格式:

SELECT 
    '["dramatic" ,"women", "political"]'::json::text =  
    '["dramatic","women","political"]'::json::text      -- yields false!
Run Code Online (Sandbox Code Playgroud)

在Postgres 9.4+中,您可以使用类型来解决此问题,类型jsonb以分解的二进制格式存储.可以比较此类型的值:

SELECT 
    '["dramatic" ,"women", "political"]'::jsonb =  
    '["dramatic","women","political"]'::jsonb           -- yields true
Run Code Online (Sandbox Code Playgroud)

所以这个查询更可靠:

SELECT * 
FROM movie_test 
WHERE tags::jsonb = '["dramatic","women","political"]'::jsonb
Run Code Online (Sandbox Code Playgroud)

阅读有关JSON类型的更多信息.

  • 最好使用jsonb而不是文本比较,因为文本比较会报告由于格式化等方面的细微差别而导致的不等结果. (3认同)
  • @poshest - `完整结果 -> '国家' -> 0 -> '城市' ->> '街道'` (2认同)