首页 > 解决方案 > 需要帮助将 CASE 中的集合返回函数移动到 LATERAL 连接

问题描述

我有一个需要重写的应用程序查询,以便可以升级数据库。我已经尝试了这里论坛中列出的几件事,例如将集合返回功能移动到横向连接,但似乎无法使其正常工作。任何帮助,将不胜感激。下面的原始查询。

   SELECT id, name, description, owner, is_private, read_scopes, edit_scopes,
          CASE 
            WHEN jsonb_typeof(json_element) = 'array' 
            THEN jsonb_array_elements(json_element)
            WHEN jsonb_exists(json_element, 'children')
            THEN jsonb_array_elements(json_element -> 'children')
            END AS json_element
        FROM children
        WHERE  jsonb_typeof(json_element) = 'array' OR jsonb_typeof(json_element) = 'object'

标签: postgresql

解决方案


您可以将决定取消嵌套的数组移动到传递给 jsonb_array_elements() 的参数中:

select id, name, j.*
from children c
  cross join jsonb_array_elements(case 
                                   when jsonb_typeof(c.json_element) = 'array' then json_element 
                                   when jsonb_typeof(c.json_element -> 'children') = 'array' then json_element -> 'children'
                                  end) as j(json_element)
where jsonb_typeof(c.json_element) = 'array'
   or jsonb_typeof(c.json_element -> 'children') = 'array'

推荐阅读