【问题标题】:Querying a jsonb array in postgres在 postgres 中查询一个 jsonb 数组
【发布时间】:2015-09-10 17:10:51
【问题描述】:

表:

CREATE TABLE appointment
(
  id bigserial NOT NULL,
  date_of_visit timestamp without time zone NOT NULL,
  symptoms text[],
  diseases text[],
  lab_tests text[],
  prescription_id bigint NOT NULL,
  medicines jsonb,
  CONSTRAINT appointment_pkey PRIMARY KEY (id),
  CONSTRAINT appointment_prescription_id_fkey FOREIGN KEY (prescription_id)
  REFERENCES prescription (id) MATCH SIMPLE
  ON UPDATE NO ACTION ON DELETE NO ACTION
 )
 WITH (
  OIDS=FALSE
 );

插入语句:

INSERT INTO appointment values(
    1,
    now(),
    '{"abc","def","ghi"}',
    '{"abc","def","ghi"}',
    '{"abc","def","ghi"}',
    1,
    '[{"sku_id": 1, "company": "Magnafone"}, {"sku_id": 2, "company": "Magnafone"}]')

我正在尝试查询 postgres 中的 jsonb 数组类型列。我手头有一些解决方案,如下所示。不知何故它不起作用错误是-Cannot extract elements from a scalar

SELECT distinct(prescription_id)
FROM  appointment
WHERE to_json(array(SELECT jsonb_array_elements(medicines) ->>'sku_id'))::jsonb ?|array['1'] 
LIMIT 2;

更新: 查询运行良好。对于其他一些行,列中有一些不需要的值,因此它没有运行。

【问题讨论】:

    标签: postgresql jsonb


    【解决方案1】:

    表中有行包含列medicines 中的标量值而不是数组。 您应该检查并正确更新数据。您可以使用此查询找到这些行:

    select id, medicines
    from appointment
    where jsonb_typeof(medicines) <> 'array';
    

    或者,您可以在查询中检查此列中值的类型:

    select prescription_id
    from (
        select distinct on (prescription_id)
            prescription_id, 
            case 
                when jsonb_typeof(medicines) = 'array' then jsonb_array_elements(medicines) ->>'sku_id' 
                else null 
            end as sku_id
        from appointment
        ) alias
    where sku_id = '1'
    limit 2;
    

    或者干脆排除where clause中的非数组值:

    select prescription_id
    from (
        select distinct on (prescription_id)
            prescription_id, 
            jsonb_array_elements(medicines) ->>'sku_id' as sku_id
        from appointment
        where jsonb_typeof(medicines) = 'array'
        ) alias
    where sku_id = '1'
    limit 2;
    

    【讨论】:

    • 最后一个查询正常!!当我运行第一个时,我得到了两个空字段。我在问题中提出的查询也可以正常工作!谢谢。
    猜你喜欢
    • 2021-05-12
    • 1970-01-01
    • 2015-11-28
    • 2018-03-29
    • 2016-06-14
    • 1970-01-01
    • 2018-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多