当我尝试从表格中选择一些记录时
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
我是否遗漏了某些内容或者我可以在哪里了解这个错误。
答案 0 :(得分:20)
您无法比较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+中,您可以使用类型jsonb
来解决此问题,该类型以分解的二进制格式存储。可以比较此类型的值:
SELECT
'["dramatic" ,"women", "political"]'::jsonb =
'["dramatic","women","political"]'::jsonb -- yields true
所以这个查询更可靠:
SELECT *
FROM movie_test
WHERE tags::jsonb = '["dramatic","women","political"]'::jsonb
详细了解JSON Types。