0

Using the following query:

select bc.name, b.* from blog b
left join blog_to_blog_category btbc on b.id = btbc.blog_id
join blog_category bc on btbc.blog_category_id = bc.id
group by b.id, bc.name
having array_agg(btbc.blog_category_id) @> array[5,6];

It will show me blogs that are in both category 5 AND 6. How do I alter this so it will show me blogs that are in either category 5 OR 6?

1 Answer 1

1

Use the overlaps operator && instead of the contains operator @> for the two arrays.

You can however simplify by not using an aggregation but just a WHERE condition (with a normal JOIN instead of the LEFT JOIN):

select bc.name, b.*
from blog b
join blog_to_blog_category btbc on b.id = btbc.blog_id
join blog_category bc on btbc.blog_category_id = bc.id
where bc.id in (5, 6)
group by b.id, bc.name

(I suspect this will also be more efficient / optimised better than the array aggregate)

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

2 Comments

Thank you. What is reason that left join shouldn't be used?
Without the having clause, you'd get all blogs (and null for the category name) when doing a left join and filtering only categories

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.