1

I'm trying to find out how to get JSON object results of selected rows, and not to show duplicated rows.
My current query:
SELECT DISTINCT ON (vp.id) jsonb_agg(jsonb_build_object('affiliate',a.*)) as affiliates, jsonb_agg(jsonb_build_object('vendor',vp.*)) as vendors FROM
affiliates a
INNER JOIN related_affiliates ra ON a.id = ra.affiliate_id
INNER JOIN related_vendors rv ON ra.product_id = rv.product_id
INNER JOIN vendor_partners vp ON rv.vendor_partner_id = vp.id
WHERE ra.product_id = 79 AND a.is_active = true
GROUP BY vp.id

The results that I receive from this is:

[
affiliates: {
affiliate: affiliate1
affiliate: affiliate2
},
vendors: {
vendor: vendor1,
vendor: vendor1,
}

As you can see in the second record, vendor is still vendor1 because there are no more results, so I'd like to also know if there's a way to remove duplicates.
Thanks.

1
  • 3
    Your output does not look consistent with the query. There should be one array of affiliates, and another array of vendors - which is not what you are showing here. Commented Dec 27, 2020 at 11:32

2 Answers 2

5

First point : the result you display here above doesn't conform the json type : the keys are not double-quoted, the string values are not double-quoted, having dupplicated keys in the same json object ('{"affiliate": "affiliate1", "affiliate": "affiliate2"}' :: json) is not be accepted with the jsonb type (but it is with the json type).

Second point : you can try to add the DISTINCT key word directly in the jsonb_agg function :

jsonb_agg(DISTINCT jsonb_build_object('vendor',vp.*))

and remove the DISTINCT ON (vp.id) clause.

You can also add an ORDER BY clause directly in any aggregate function. For more information, see the manual.

Sign up to request clarification or add additional context in comments.

Comments

0

You could aggregate first, then join on the results of the aggregates:

SELECT a.affiliates, v.vendors 
FROM (
  select af.id, jsonb_agg(jsonb_build_object('affiliate',af.*)) as affiliates
  from affiliates af
  group by af.id
) a  
  JOIN related_affiliates ra ON a.id = ra.affiliate_id
  JOIN related_vendors rv ON ra.product_id = rv.product_id
  JOIN (
    select vp.id, jsonb_agg(jsonb_build_object('vendor',vp.*)) as vendors
    from vendor_partners vp
    group by vp.id
  ) v ON rv.vendor_partner_id = v.id
WHERE ra.product_id = 79 
 AND a.is_active = true

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.