一尘不染

运算子不存在:json = json

json

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

    SELECT * FROM movie_test WHERE tags = ('["dramatic","women", "political"]'::json)

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

我错过了一些东西吗,或者我可以从那里学到一些有关此错误的信息。


阅读 331

收藏
2020-07-27

共1个答案

一尘不染

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

SELECT * 
FROM movie_test 
WHERE tags::text = '["dramatic","women","political"]'

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

SELECT 
    '["dramatic" ,"women", "political"]'::json::text =  
    '["dramatic","women","political"]'::json::text      -- yields false!

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

SELECT 
    '["dramatic" ,"women", "political"]'::jsonb =  
    '["dramatic","women","political"]'::jsonb           -- yields true

因此此查询更加可靠:

SELECT * 
FROM movie_test 
WHERE tags::jsonb = '["dramatic","women","political"]'::jsonb

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

2020-07-27