简体   繁体   中英

postgres how to make conditional join

I have json field that contains object or array of objects. I need to join one key from object if field contains only one object or use lateral join if there is array. I use jsonb_typeof() to determine whether it array or object and want to do something like this

SELECT DISTINCT ON
    (id) id,
    jsonb_typeof(field) AS type,
    CASE WHEN jsonb_typeof = 'object' THEN field->>'key' END
FROM
    test_table
    CASE WHEN jsonb_typeof = 'array' THEN lateral JOIN expression

is it possible to do something like this? At this point I get:

undefined column error(jsonb_typeof)

... in when condition

you can transform data in a subquery:

  1. unnest the arrays with json_array_elements
  2. union the unnested set with objects set
  3. use this temporary set with the uniform object column in a normal join (by key or whatever)

You can split this into two subqueries:

SELECT DISTINCT ON (id) id, jsonb_typeof(field) AS type,
    CASE WHEN jsonb_typeof = 'object' THEN field->>'key' END
FROM ((SELECT id, jsonb_typeof(field) AS type, field->>'key' as col
       FROM test_table
       WHERE jsonb_typeof(field) = 'object'
      ) UNION ALL
      (SELECT id, jsonb_typeof(field) AS type, field->>'key' as col
       FROM test_table LEFT JOIN LATERAL
            . . .
       WHERE jsonb_typeof(field) = 'array'
      ) 
     ) t
ORDER BY id, ???;

Note that when you use DISTINCT ON , you should be using ORDER BY as well. Usually, there are additional columns beyond the DISTINCT ON keys to determine which row you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM