问题
I have the following tables (with given columns):
houses (id)
users (id, house_id, active)
custom_values (name, house_id, type)
I want to get all the (distinct) houses and the count of associated users that:
- have at least 1 associated
custom_value
whichname
column contains the string 'red' (case insensitive) AND the custom_value columntype
value is 'mandatory'. - have at least 100 associated users which status column is 'active'
How can I run this query in PostgreSQL?
Right now I have this query (which was answered in Get records where associated records name contain a string AND associated record count is bigger than threshold), but I don't know how to select the count of users too (:
select h.*
from houses
where
exists (
select 1
from custom_values cv
where cv.house_id = h.house_id and cv.type = 'mandatory' and lower(cv.name) = 'red'
)
and (
select count(*)
from users u
where u.house_id = h.house_id and u.status = 'active'
) >= 100
回答1:
You can turn the subquery to a lateral join:
select h.*, u.no_users
from houses h
cross join lateral (
select count(*) no_users
from users u
where u.house_id = h.house_id and u.status = 'active'
) u
where
u.cnt >= 100
and exists (
select 1
from custom_values cv
where cv.house_id = h.house_id and cv.type = 'mandatory' and lower(cv.name) = 'red'
)
来源:https://stackoverflow.com/questions/61750016/condition-on-count-of-associated-records-in-sql