sql - Rails / SQL:查找没有孩子或所有孩子都有条件的父母
问题描述
我需要找到没有孩子或所有孩子都完全有条件的父母(状态 = 1)。
class Parent
has_many :children
end
class Child
enum status: [ :confirmed, :not_confirmed ]
belongs_to :parent
end
我知道第一部分,即寻找没有孩子的父母。
Parent.joins(:children).where('count(children) = 0')
铁轨回答。
解决方案
由于您使用的是 Postgres,因此您可以使用NOT EXISTS
查询:
# Parents with no children
Parent.where.not('exists (?)', Child.where('children.parent_id = parents.id').select(1))
这个查询比任何需要连接的查询执行得更好,因为它EXPLAIN
会告诉你 Postgres 将通过一个Nested Loop Anti Join
操作来完成这个。
推荐阅读
- angular - ng2-image-viewer 与最新版本的 angular (11+) 不兼容
- c - 即使使用了 malloc,C realloc() 也会出现无效指针错误
- dependency-injection - HttpContext.RequestServices.GetRequiredService
未能获得注册服务 - node.js - 无法使用打字稿在nodejs中导入模块
- javascript - setInterval 功能在滚动功能上无法正常工作
- python - 您可以使用格式化的字符串在 Python 的 selenium 中按任何类别(xpath、css 等)查找元素吗?
- flutter - 子容器没有完全覆盖父容器,留下一个很小的填充
- javascript - 如何使用 jquery ajax 从 .net core 5 下载文件
- kerberos - 如何使用 jldap 库在 openldap 中解析 Kerberos 的属性“krbprincipalkey”?
- inno-setup - Inno Setup 的应用程序发布者使安装程序未显示在 Windows 7 UAC 提示中,但在 Windows 10 上显示