【问题标题】:Select from JSONB field with WHERE clause从带有 WHERE 子句的 JSONB 字段中选择
【发布时间】:2015-04-11 19:22:06
【问题描述】:

刚安装 9.4 并尝试使用 JSONB 字段类型。

我已经制作了一个带有 jsonb 字段的表格,并且可以从中进行选择:

select statistics->'statistics'->'all_trades'->'all'->'all_trades_perc_profit' as profitable_perc FROM  trade_statistics

工作正常。

现在我想根据字段值过滤结果:

select statistics->'statistics'->'all_trades'->'all'->'all_trades_perc_profit' as profitable_perc FROM  trade_statistics WHERE profitable_perc > 1

//There is no "profitable_perc" column

不起作用。

如果我尝试将结果转换为双精度,也不起作用。

select cast(statistics->'statistics'->'all_trades'->'all'->'all_trades_perc_profit' as double precision) as profitable_perc FROM  trade_statistics

//cant convert jsonb into double precision

如果是jsonb,我应该如何在WHERE子句中使用选择结果?

【问题讨论】:

    标签: postgresql jsonb


    【解决方案1】:

    必须进行三个更正:

    • 将查询包装在子查询中 - 您不能在 WHERE 子句中引用 SELECT 列表别名
    • 使用->> 运算符获取文本形式的值
    • 将文本值转换为整数,以便进行比较

      SELECT *
        FROM (
          SELECT (statistics->'statistics'->'all_trades'->'all'->>'all_trades_perc_profit')::integer as profitable_perc
              FROM  trade_statistics
        ) sq1
        WHERE profitable_perc > 1
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-05
      • 1970-01-01
      • 2014-09-18
      • 2019-02-12
      • 1970-01-01
      • 1970-01-01
      • 2011-07-05
      相关资源
      最近更新 更多