مرکزی مواد پر جائیں
eLearner.app
ماڈیول 15 · سبق 2 از 2کورس میں 57/57~15 min
ماڈیول اسباق (2/2)

JSON جمع کرنے کے افعال

JSON Aggregation Functions

The integration is bidirectional. The database doesn't have to limit itself to parsing JSON: it can build it. Imagine if your API and Node.js didn't have to do the dirty, intensive work of serializing nested objects into JSON, because the DB delivered them already built straight from disk.

Building Objects and Arrays

Instead of the classic mass aggregation or string concatenation (String_agg), we turn to these functions:

  • json_build_object(key, value, ...) or jsonb_build_object(...)
  • json_agg(...) or jsonb_agg(...)
SQL
SELECT json_build_object('name', first_name, 'city', city) AS data
FROM customers;

You'll see rows printed containing { "name": "...", "city": "..." }, perfectly compliant.

ورزش#sql.m15.l2.e1
کوششیں: 0لوڈ ہو رہا ہے…

From the 'customers' table, return the data as JSON rows, mapped with \`json_build_object\`. Map two keys: 'name' bound to 'first_name', and 'mail' bound to 'email'. Use \`AS customer_doc\` for the column.

ایڈیٹر لوڈ ہو رہا ہے…
اشارہ دکھائیں۔

json_build_object('name', first_name, 'mail', email)

3 کوششوں کے بعد حل دستیاب ہے۔

ورزش#sql.m15.l2.e2
کوششیں: 0لوڈ ہو رہا ہے…

For each order (\`order_id\`), build in a single unit all the \`product_id\`s it includes. From the 'order_items' table, run \`GROUP BY order_id\`. Then select \`order_id\` and accumulate into a JSON array (JSON_AGG) just the \`product_id\` data. Name the array \`products\`.

ایڈیٹر لوڈ ہو رہا ہے…
اشارہ دکھائیں۔

JSON_AGG(product_id) plus a classic group by to gather the data.

3 کوششوں کے بعد حل دستیاب ہے۔