首页 > 解决方案 > 获取关联记录名称包含字符串且关联记录计数大于阈值的记录

问题描述

我有以下表格:

houses 
users
custom_values

用户有一个 FK 到房子 (house_id) - 一个房子有很多用户 A custom_value 有一个 FK 到房子 (house_id) - 一个房子有很多自定义值

我想获得所有(独特的)房屋:

如何在 PostgreSQL 中运行此查询?

标签: sqlpostgresqljoinselectgroup-by

解决方案


您可以使用两个相关的子查询:一个带有existson custom_values,另一个带有不等式条件的相关数量users

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

推荐阅读