如何将记录类型转换为jsonb或使用诸如<@ bewteen jsonb之类的某些运算符并在postgresql中进行记录?

时间:2019-04-01 02:37:12

标签: sql json postgresql

我正在使用postgresql 10.6并遇到一些问题。我试图在pg中使用<@,但它提醒我“运算符不存在:jsonb <@记录”。

我使用jsonb_to_set将jsonb转换为记录,但记录不支持<@。

owner_org js jsonb类型,例如[1、2、3]

SELECT
    org."name" AS NAME,
    COUNT ( * ) AS num 
FROM
    project
    LEFT JOIN "user" ON "user"."id" = (
    SELECT
    to_number( OPERATOR ->> 'id', '99999999' ))
    LEFT JOIN org ON (
    SELECT
    to_number( "user".org_id ->> 0, '99999999' )) = org."id" 
WHERE
    OPERATOR ->> 'id' <> '0' 
    AND project.deleted_at IS NULL 
    AND project.created_at >= '2018-01-20 14:00:00' 
    AND project.created_at <= '2018-09-29 17:00:00' 
    AND project.deleted_at IS NULL 
    AND owner_org::jsonb  <@ (
        '16',
        '20',
        '22',
        '23',
        '24',
        '25',
        '26',
        '27',
        '28',
        '29',
        '30',
        '31',
        '32',
        '33' 
    ) 
GROUP BY
    org."name"

我期望“ Org_A” 1的输出,但实际输出是

LINE 18:  AND jsonb_to_record(owner_org)  <@ (
                                          ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

1 个答案:

答案 0 :(得分:1)

('16', '20', ...)是PostgreSQL中的行文字,但是<@ operator(“包含”)在两边都希望jsonb。如果您在右侧使用JSON数组,则应该运气更好:

owner_org::jsonb <@ '["16","20","22", ...]'::jsonb