filmov
tv
#20 ROW_TO_JSON: Postgresql, How to build JSON using row_to_json function from two related tables.

Показать описание
The source code above creates two temporary tables named "territory_group" and "territories" in PostgreSQL database.
The "territory_group" table has two columns named "group_id" and "group_name", with "group_id" being the primary key.
The "territories" table has three columns named "group_id", "territory_id", and "territory_name". The table's primary key is a composite key formed by "group_id" and "territory_id", and it has a foreign key constraint referencing the "group_id" column of the "territory_group" table.
After creating these tables, the source code inserts some data into them. The first insertion statement inserts a row into the "territory_group" table with values 1 and 'North' for "group_id" and "group_name" columns, respectively.
The second insertion statement inserts two rows into the "territories" table, with values (1, 1, 'North Dakota Territory') and (1, 2, 'South Dakota Territory') for "group_id", "territory_id", and "territory_name" columns, respectively.
Finally, the source code performs a select statement that retrieves data from both tables using a join operation, groups the results by "group_id", and aggregates the "territory_id" and "territory_name" columns of the "territories" table into a JSON array using the "json_agg" and "json_build_object" functions. The "row_to_json" function is then used to convert the resulting rows into JSON format.
The "territory_group" table has two columns named "group_id" and "group_name", with "group_id" being the primary key.
The "territories" table has three columns named "group_id", "territory_id", and "territory_name". The table's primary key is a composite key formed by "group_id" and "territory_id", and it has a foreign key constraint referencing the "group_id" column of the "territory_group" table.
After creating these tables, the source code inserts some data into them. The first insertion statement inserts a row into the "territory_group" table with values 1 and 'North' for "group_id" and "group_name" columns, respectively.
The second insertion statement inserts two rows into the "territories" table, with values (1, 1, 'North Dakota Territory') and (1, 2, 'South Dakota Territory') for "group_id", "territory_id", and "territory_name" columns, respectively.
Finally, the source code performs a select statement that retrieves data from both tables using a join operation, groups the results by "group_id", and aggregates the "territory_id" and "territory_name" columns of the "territories" table into a JSON array using the "json_agg" and "json_build_object" functions. The "row_to_json" function is then used to convert the resulting rows into JSON format.