JION数据类型上的UNION ALL

Die*_*oza 6 postgresql union json compare postgresql-9.2

我需要在Postgres 9.2中使用JSON数据类型执行UNION ALL,但在执行此操作时,Postgres会回复此错误:

ERROR: could not identify an equality operator for type json SQL  
state: 42883  
Character: 9
Run Code Online (Sandbox Code Playgroud)

查询:

(select cast('{"billingcode" : "' || billingcode || '"}' as JSON)
 from billing_2012_08 limit 10)
union
(select cast('{"charged" : "' || charged || '"}' as JSON)
 from sending_response_2012_08 limit 10)
Run Code Online (Sandbox Code Playgroud)

这里有什么问题?

正如我所发现的,似乎Postgres没有为json数据类型定义一个相等的运算符.如果这是正确的,为什么?

作为一个试图找出问题的例子,这很好用:

(select cast('{"billingcode" : "' || billingcode || '"}' as JSON)
 from billing_2012_08 limit 10)
union all
(select cast('{"charged" : "' || charged || '"}' as JSON)
 from sending_response_2012_08 limit 10)
Run Code Online (Sandbox Code Playgroud)

请注意,UNION ALL只是"添加"结果(而不仅仅是UNION,它消除了重复值).

Erw*_*ter 9

测试JSON值是否"相等"并非易事.除其他外,属性可以按任何顺序排序,二进制或文本表示可以完全不同,而仍然根据JSON规范限定为相等.这就是为什么在PostgreSQL中没有定义相等运算符的原因.

如果您对文本表示相同(从示例中看起来)感到满意,您可以UNION ALL使用text列并在json以后进行强制转换:

SELECT json_col::json
FROM (
   (SELECT '{"billingcode" : "' || billingcode || '"}'::text AS json_col
    FROM   billing_2012_08 LIMIT 10)
   UNION ALL
   (SELECT '{"charged" : "' || charged || '"}'::text
    FROM   sending_response_2012_08 LIMIT 10)
   ) sub
Run Code Online (Sandbox Code Playgroud)

- > SQLfiddle演示.