在PostgreSql中具有关联的子句 [英] Having clause in PostgreSql with association

查看:99
本文介绍了在PostgreSql中具有关联的子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我拥有的协会

Instructor has many Instructor Students

InstructorStudent has many Student Contacts

学生联系人表的一个字段primary_contact具有布尔类型。

Student Contacts table has one field primary_contact which has boolean type.

我要指导没有任何学生联系或所有
学生联系人的primary_contact为false的学生。

I want to instructor students who has not any student contacts or all student contacts's primary_contact is false.


eg

e.g

教师学生1有3个学生联系人,而所有3个学生
联系人的主要联系人字段均为false。比我想要的记录

instructor student 1 has 3 student contacts and all 3 student contacts's primary contact field is false. than i want that record

教师学生2有3个学生联系人,其中2个学生
联系人的主要联系人字段为false,而其他学生联系人的
主要学生

instructor student 2 has 3 student contacts in which 2 student contacts's primary contact field is false and other student contact's primary contact is true than i dont want that record.

我提出了一个查询,但我不怎么写hading子句。

i made one query but i dont how to write having clause.

Instructor.joins(:instructor_students =>:student_contacts)
.where( admin_users.id =?AND student_contacts.primary_contact =
?,7,false)
.select( student_contacts.instructor_student_id,count(student_contacts.primary_contact)as sc_count)
.group( student_contacts.instructor_student_id)
.having( count(student_contacts.primary_contact)=?,动态值)

任何帮助将不胜感激。

Any help will be appreciated. Thank you in advance.

推荐答案

请尝试此操作,因为您说过想要 InstructorStudent 对象,因此您应该加入该表。

Please try this, as you said you want InstructorStudent object so you should join on that table.

InstructorStudent.joins(:student_contacts).where("student_contacts.primary_contact = 
   ?",false)
  .select("student_contacts.instructor_student_id,count(student_contacts.primary_contact) as sc_count")
    .group("student_contacts.instructor_student_id")
    .having("count(student_contacts.primary_contact) = ?",Dynamic_value)

这篇关于在PostgreSql中具有关联的子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆