sql - 获取关联记录名称包含字符串且关联记录计数大于阈值的记录
问题描述
我有以下表格:
houses
users
custom_values
用户有一个 FK 到房子 (house_id) - 一个房子有很多用户 A custom_value 有一个 FK 到房子 (house_id) - 一个房子有很多自定义值
我想获得所有(独特的)房屋:
- 至少有 1 个关联
custom_value
哪个name
列包含字符串“red”(不区分大小写)并且 custom_value 列type
值为“强制”。 - 至少有 100 个关联用户,其状态列为“活动”
如何在 PostgreSQL 中运行此查询?
解决方案
您可以使用两个相关的子查询:一个带有exists
on 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
推荐阅读
- vue.js - 如何在退出时停止 Vue.js 3 watch() API 触发
- php - 我的翻译覆盖了所有值 - voyager 1.4.0
- machine-learning - RandomForestClassifier 如何进行分类?
- random - BigQuery:对每组不同数量的行进行采样
- html - 我可以使用 CSS 定位列表中的删除行吗?
- android - 在 android 10 中是否阻止了对具有 TLS 1.0 的服务器的 AJAX 请求?
- thingsboard - Thingsboard - - 获取链接到资产的设备列表
- excel - 在条件格式中使用 IF 函数更改用户输入的值
- bash - grep 输出到 pip 安装
- heroku - MERN Stack - 在 Heroku 上部署时收到错误