在postgres中查询jsonb数组

时间:2015-06-24 13:12:32

标签: postgresql jsonb

表:

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;

更新: 查询运行得很好。列中有一些不需要的值,因为它没有运行。

1 个答案:

答案 0 :(得分:2)

表中有些行包含列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;