代码之家  ›  专栏  ›  技术社区  ›  A J

基于json从表中获取数据

  •  0
  • A J  · 技术社区  · 7 年前

    我有一个表有一列“sample_column”,这是jsonb。

    有人能告诉我如何根据postgresql中的“示例列”选择数据吗?

    示例列{“a”:[]}中的数据示例
    {“a”:[1,2,3]}

    如果sample_列的值为{“a”:[]},我想获取所有数据

    以下是我所做的: Select * from sample_table where sample_column = '{"a": []}'

    我收到错误:json类型的输入语法无效。

    任何帮助都将不胜感激。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Abdou    7 年前

    如果 a 关键是差异化,应做到以下几点:

    select * from sample_table where sample_column->'a' = '[]';
    

    如果你要处理更多的钥匙,你可能需要使用 AND 或者 OR 接线员,取决于你想做什么。下面是一个示例:

    -- Create table and insert some rows in it
    create table sample_table (sample_column jsonb);
    insert into sample_table values ('{"a": []}'), ('{"b": 2, "a": [2,3]}'), ('{"c": 20}');
    
    -- Use an OR operator to get rows where the value for the "b" key is greater 1
    -- or the value for the "c" key is equal to 20.
    select * from sample_table where sample_column->'b' > '1' or sample_column->'c' = '20';
    

    你应该得到这样的东西:

     {"a": [2, 3], "b": 2}
     {"c": 20}
    

    要获取样本列中除{“a”:[]}以外的所有值的数据,可以执行以下操作:

    select * from sample_table where sample_column != '{"a": []}'::jsonb;
    

    ::jsonb 将字符强制转换为 jsonb 类型,这将使比较成为可能。

    我希望这证明是有用的。