0

桌子:

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;

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

4

1 回答 1

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;
于 2015-06-24T14:11:25.910 回答