加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

postgresql – 如何分组/选择JSON类型列(PG :: UndefinedFunctio

发布时间:2020-12-13 16:05:47 所属栏目:百科 来源:网络整理
导读:我想做 MODEL.select("brief_content").group("brief_content") 这是表格方案, :id = :integer,:content = :json,:brief_content = :json 但我得到了错误, 我该怎么办,谢谢 companyAlarmLog Load (0.9ms) SELECT company_alarm_logs.id,company_alarm_logs.n
我想做

<MODEL>.select("brief_content").group("brief_content")

这是表格方案,

:id => :integer,:content => :json,:brief_content => :json

但我得到了错误,

我该怎么办,谢谢

companyAlarmLog Load (0.9ms)  SELECT company_alarm_logs.id,company_alarm_logs.name,company_alarm_logs.utc_time,company_alarm_logs.company_alarm_test_id,company_alarm_logs.brief_content,brief_content FROM "company_alarm_logs" GROUP BY brief_content ORDER BY utc_time
E,[2014-06-24T09:40:39.069988 #954] ERROR -- : PG::UndefinedFunction: ERROR:  could not identify an equality operator for type json
LINE 1: ...t,brief_content FROM "company_alarm_logs"  GROUP BY brief_cont...
                                                             ^
: SELECT company_alarm_logs.id,brief_content FROM "company_alarm_logs"  GROUP BY brief_content  ORDER BY utc_time
Hirb Error: PG::UndefinedFunction: ERROR:  could not identify an equality operator for type json
LINE 1: ...t,brief_content FROM "company_alarm_logs"  GROUP BY brief_cont...

解决方法

不幸的是,没有简单的方法可以在9.3中直接进行json相等测试.

9.3的json类型没有相等运算符,因为它接受带有重复键的json(正如许多实现所期望的那样).目前尚不清楚{“a”:1,“a”:2}是否与{“a”:1}“相等”.

9.4添加了jsonb,它在最后一键获胜的基础上折叠重复键,使得相等无误.

regress=# SELECT '{"a":1,"a":2}'::json = '{"a":1}'::json;
ERROR:  operator does not exist: json = json
LINE 1: SELECT '{"a":1,"a":2}'::json = '{"a":1}'::json;
                                      ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

regress=# SELECT '{"a":1,"a":2}'::jsonb = '{"a":1}'::jsonb;
 ?column? 
----------
 f
(1 row)

不幸的是,这意味着你无法在9.3中完成你想做的事.

你可以为json编写一个自定义相等运算符 – 也许只是将两者都转换为文本并比较那种方式,但是它会对待{“a”:1,“b”:2}和{“b”:2,“a” :1}不平等.

更好的选择是安装PL / V8并使用V8 JavaScript引擎的json操作来执行相等比较.

为json定义一个等于运算符,然后使用该运算符定义一个简单的b-tree opclass.两者在SQL级别都很简单 – 请参阅CREATE OPERATOR和CREATE OPERATOR CLASS.

完成后,您将能够在9.3中使用GROUP BY json值.

或者你可以安装9.4 beta1并使用jsonb.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读