sql >> Base de Datos >  >> RDS >> PostgreSQL

PostgreSQL 9.4:Tabla de agregación/unión en la identificación del campo JSON dentro de la matriz

La idea básica es que su consulta debe esperar que su json esté estructurado de cierta manera, de lo contrario, se vuelve realmente complejo. Según la estructura esperada, podemos dividir la estructura json en columnas usando json_to_recordset y reconstruirlo con información adicional usando json_build_object y json_agg .

WITH tab_properties_with_expanded_data_type AS (
    SELECT
      content_type.id AS content_type_id,
      tab.name AS tab_name,
      json_agg(
          -- re-build the property object, but with additional data_type information
          json_build_object(
              'name', property.name,
              'order', property.order,
              'help_text', property.help_text,
              'description', property.description,
              'data_type', json_build_object('id', data_type.id, 'html', data_type.html)
          )
      ) AS tab_properties
    FROM content_type,
      json_to_recordset(content_type.tabs) AS tab(name TEXT, properties JSON),
      json_to_recordset(tab.properties) AS property(name TEXT, "order" INTEGER, help_text TEXT, description TEXT, data_type INTEGER)
      LEFT JOIN data_type ON data_type.id = property.data_type
    GROUP BY 
      content_type.id, 
      tab.name
)
SELECT
  tab_properties_with_expanded_data_type.content_type_id AS id, 
  json_agg(
      -- rebuild the tab object
      json_build_object(
          'name', tab_properties_with_expanded_data_type.tab_name,
          'properties', tab_properties_with_expanded_data_type.tab_properties
      )
  )
FROM tab_properties_with_expanded_data_type
GROUP BY 
  tab_properties_with_expanded_data_type.content_type_id

Esto funciona, pero es muy limitado en términos de flexibilidad:tengo que enumerar explícitamente todos los campos de sus pestañas y propiedades y espero que el documento tenga una estructura específica. Pero es un buen comienzo :)