where on multiple join postgresql

All we need is an easy explanation of the problem, so here it is.

I have problem when query using postgresql
I have several tables:

numbers:

id phone
1 08211111
2 08211112

domains:

id name is_blacklisted
1 abc.com 0
2 123.com 0
3 456.com 1

domain_groups:

id name
1 alphabet
2 numeric

domain_group_domains:

domain_group_id domain_id
1 1
2 2
2 3

number_domain_history:

number_id domain_id times
1 1 1
1 2 2
3 3 2

number_domain_group_history:

number_id domain_group_id times
1 1 1
1 2 2
3 2 2

if I want to select number by domain history where domain.is_blacklisted = 0:

select numbers.id from numbers
left join number_domain_history on number_domain_history.number_id = numbers.id
where number_domain_history.domain_id not in (select domain_id from domains where is_blacklisted = 1)
group by numbers.id
limit 1000

The problem is how I can search number by domain_group that perform same blacklist since blacklisted only available in number_domain_history?

I have try with:

select numbers.id from numbers
left join number_domain_history on number_domain_history.number_id = numbers.id
left join number_domain_group_history on number_domain_group_history.
where number_domain_history.domain_id not in (select domain_id from domains where is_blacklisted = 1)
group by numbers.id
limit 1000

But the result is not like what I expect to return, I still get data from domain_group that the domain already blacklisted.

Is there any workaround?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

if I want to select number by domain history where
domain.is_blacklisted = 0:

You only need three tables:

  1. numbers
  2. domains
  3. number_domain_history

You can use a simple inner join:

select n.phone
from numbers n 
inner join number_domain_history ndh on ndh.number_id=n.id
inner join domains d on ndh.domain_id=d.id
where d.is_blacklisted=0
group by n.phone;

Result:

phone
08211111

Demo

How can I perform search by times on number_domain_group_history ? ex:
number_domains_group_history.times > 0

Simple , add another join condition.

inner join number_domain_group_history ndgh on ndgh.number_id=n.id


select n.phone
from numbers n 
inner join number_domain_history ndh on ndh.number_id=n.id
inner join domains d on ndh.domain_id=d.id
inner join number_domain_group_history ndgh on ndgh.number_id=n.id
where d.is_blacklisted=0
and ndgh.times > 0
group by n.phone;

Demo

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply