首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >PostgreSQL -无法识别类型json的相等运算符

PostgreSQL -无法识别类型json的相等运算符
EN

Stack Overflow用户
提问于 2018-01-24 18:40:45
回答 3查看 23.3K关注 0票数 7

我有以下疑问:

代码语言:javascript
运行
复制
SELECT 
  distinct(date(survey_results.created_at)), 
  json_build_object(
    'high', 
    ROUND( 
      COUNT(*) FILTER (WHERE ( scores#>>'{medic,categories,motivation}' in('high', 'medium'))) OVER(order by date(survey_results.created_at) ) * 1.0 / 
      (
        CASE (COUNT(*) FILTER (WHERE (scores#>>'{medic,categories,motivation}' in('high','medium','low'))) OVER(order by date(survey_results.created_at))) 
        WHEN 0.0 THEN 1.0 
        ELSE (COUNT(*) FILTER (WHERE (scores#>>'{medic,categories,motivation}' in('high','medium','low'))) OVER(order by date(survey_results.created_at))) 
        END)* 100, 2 ) ) AS childcare FROM survey_results GROUP BY date, scores ORDER BY date asc; 

问题出在使用distinct(date(survey_results.created_at))上。这样,查询就会返回错误:

could not identify an equality operator for type json

下面是显示问题数据库小提琴:

https://www.db-fiddle.com/f/vUBjUyKDUNLWzySHKCKcXA/1

我怎么才能修复它呢?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-01-24 18:48:39

使用jsonb_build_object。请注意json之后的二进制文件的b

票数 13
EN

Stack Overflow用户

发布于 2018-01-24 18:52:41

问题出在使用distinct(date(survey_results.created_at))

不是的。问题在于使用DISTINCT --即is 而不是a function。它始终应用to all columns of the resultdistinct(a), bdistinct a, (b)distinct a, b相同。正因为如此,distinct会尝试比较第二列的相同值,该列的类型为json,不能与=进行比较

如果你只想要最新的值,你可以用Postgres的distinct on ()操作符来实现:

代码语言:javascript
运行
复制
SELECT distinct on (date(survey_results.created_at)) 
       date(survey_results.created_at) as date,
       json_build_object('high', 
        ROUND( 
      COUNT(*) FILTER (WHERE ( scores#>>'{medic,categories,motivation}' in('high', 'medium'))) OVER(order by date(survey_results.created_at) ) * 1.0 / 
      (
        CASE (COUNT(*) FILTER (WHERE (scores#>>'{medic,categories,motivation}' in('high','medium','low'))) OVER(order by date(survey_results.created_at))) 
        WHEN 0.0 THEN 1.0 
        ELSE (COUNT(*) FILTER (WHERE (scores#>>'{medic,categories,motivation}' in('high','medium','low'))) OVER(order by date(survey_results.created_at))) 
        END)* 100, 2 ) ) AS childcare 
FROM survey_results 
GROUP BY date, scores 
ORDER BY date asc; 

order by结合使用的distinct on ()ON ()部件中指定的列的后续相同值选取第一行。在这种情况下,它将返回最早的日期。如果需要“最新”行,请将排序顺序更改为desc

https://www.db-fiddle.com/f/vUBjUyKDUNLWzySHKCKcXA/1

票数 8
EN

Stack Overflow用户

发布于 2022-01-08 04:20:40

迁移到使用JSONB,您就不会有这个问题。

这是几年前Postgres 9.4问世时遵循的标准建议。这是Ruby on Rails社区中的一个帖子,它描述了迁移到JSONB作为解决方案。

这就是线程:https://github.com/rails/rails/issues/17706

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48420438

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档