如何在连接表上编写条件查询

问题描述 投票:0回答:1

我正在尝试使用 Rails ORM 编写查询。假设有两个模型。

class College

has_many :students
class Student

belongs_to :college

Student
表有一列名为
result
,可以是
pass
fail
现在,我只想获取所有学生都有
passed
的大学列表。

我尝试了以下方法

College.join(:students).group('colleges.id, students.results').select('colleges.id, count(students) as students_count').where(students: {result: 'pass'}).having('count(*) = students_count')

但我收到此错误:

Caused by PG::UndefinedColumn: ERROR:  column "students_count" does not exist

ruby-on-rails database postgresql orm relational-database
1个回答
0
投票

最好的方法是使用否定子查询:

College.where.not(id: Student.select(:college_id).where(result: "fail"))
© www.soinside.com 2019 - 2024. All rights reserved.