cannot extract elements from a scalar

狂风中的少年 提交于 2021-02-09 09:14:10

问题


I have 2 tables company and contacts. Contacts has addresses JSONB column. I tried a select statement with a join on contacts.linked_to_company and using jsonb_array_elements(company.addresses) but I get error 'cannot extract elements from a scalar' which I understand is because some entries do have [null] in column address. I have seen answers to use coalesce or a CASE statement. Coalesce I could get to not work and CASE example is in the select statement how do use it in a join? Here is the sql

SELECT company.id,
trading_name, 
nature_of_business, 
t.id contactID, 
address->>'PostCode' Postcode,
position_in_company
FROM contact t FULL JOIN company ON (t.company_linked_to = company.id ),
jsonb_array_elements(t.addresses) address
  WHERE
 t.company_linked_to ='407381';

here is example jsonb

[{"PostCode":"BN7788","Address":"South Street","AddressFull":"","Types":[{"Type":"Collection"}]}]

回答1:


You can try one of these (instead of jsonb_array_elements(t.addresses) address):

jsonb_array_elements(case jsonb_typeof(addresses) when 'array' then addresses else '[]' end) address
-- or
jsonb_array_elements(case jsonb_typeof(addresses) when 'array' then addresses else '[{"PostCode": null}]' end) address

The first one hides rows with improper json format of the column, the second one gives null for them.

However, the problem actually stems from that one or more values in the column is not a json array. You can easily fix it with the command:

update contact
set addresses = '[null]'
where jsonb_typeof(addresses) <> 'array' or addresses = '[]';

After this correction you won't need case in jsonb_array_elements().



来源:https://stackoverflow.com/questions/50296102/cannot-extract-elements-from-a-scalar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!