Rails 中 WHERE 子句中的 ALL 运算符

ALL operator in WHERE clause in Rails

关联如下图

InstructorStudent has_many :fees

Fee belongs_to :instructor_student

我想获得在所有给定数组中都有每月详细信息的讲师学生。如果其中任何一个都没有每月详细信息,那么它不应该 return 任何记录。

due_month = ["2017-01-01","2017-02-01",,"2017-03-01"]

以下是我试过的查询,我想得到 InstructorStudent 属于所有给定的三个 due_month,如果任何月份没有数据那么它应该 return nil:

@fee_paid = 
InstructorStudent.first.joins(:fees).where("fees.monthly_detail = 
ALL(ARRAY[?]::date[]) AND fees.course_type = ?", due_month.map{|i| i 
},"per month");

编辑 1:

@erwin-brandstetter 这是我的最终查询

InstructorStudent.where("
  instructor_students.Id IN (?)",Instructor.find(17).per_month_active_student
).joins(
  "INNER JOIN fees ON fees.instructor_student_id = instructor_students.id LEFT OUTER JOIN fee_payment_notifications ON fee_payment_notifications.fee_id = fees.id"
).where(
  "fee_payment_notifications.status <> ? AND
  fees.monthly_detail = ANY(ARRAY[?]::date[]) AND
  fees.course_type = ? AND
  fees.payment_status <> ?"
  , 'Paid',dueMonth,"per month", "Due"
).group(
  'fees.instructor_student_id'
).
having(
  'count(*) = ?', dueMonth.length
)

协会:

InstructorStudent has_many Fees
Fee belongs_to instructor_student

Fee has_many fee_payment_notifications
FeePaymentNotifications belongs to fee

这里是我为吸引讲师学生所做的工作。在 dueMonth 数组中有 fees.monthly_detail,fees.payment_status 是 "Due",Fees.course_type 是 "per month" fee_payment_notifications 不应该是 "Paid".

不一定总是fee_payment_notifications存在。 所以,如果 fee 有 fee_payment_notifications,那么它应该检查它的状态。 如果没有任何 fee_payment_notifications 则应该获取记录。 如果有 fee_payment_notifications 且状态为 "Paid",则不应获取记录。

您可以将月份转换为 Ruby 的日期 class 并让 ActiveRecord 完成工作:

due_month= ["2017-01-01","2017-02-01","2017-03-01"]    
fee_paid = InstructorStudent.joins(:fees).where("fees.monthly_detail" => due_month.map{|month| Date.parse month}, "fees.course_type" => "per month")

这是 的情况。

实际 table 定义(标准 1:n 关系,被 Ruby ORM 隐藏)将是这样的:

CREATE TABLE instructor_student (
   id serial PRIMARY KEY
   name ...
);

CREATE TABLE fees (
   id serial PRIMARY KEY
 , instructor_student_id integer NOT NULL REFERENCES instructor_student
 , course_type ...
 , monthly_detail date
 , UNIQUE (instructor_student_id, course_type, monthly_detail)
);

您的查询尝试有效地尝试针对给定数组中的多个值测试 fees 中的每一行,总是 失败,而数组的元素是不相同。 一个值不能与多个其他值相同。您需要一种不同的方法:

SELECT instructor_student_id
FROM   fees
WHERE  course_type = ?
AND    monthly_detail = ANY(ARRAY[?]::date[])  -- ANY, not ALL!
GROUP  BY instructor_student_id
HAVING count(*) = cardinality(ARRAY[?]::date[]);

这是假设数组中的 distinct 值和 table 费用中的唯一条目,例如 UNIQUE 我在上面添加的约束。否则,计数不可靠,您必须使用更复杂的查询。这是一个选项库:

  • How to filter SQL results in a has-many-through relation

如您所见,我根本没有涉及 table instructor_student。虽然引用完整性是通过 FK 约束强制执行的(就像通常那样),但我们可以单独使用 fees 来确定符合条件的 instructor_student_id。如果您需要从主 table 中获取更多属性,请在第二步中执行此操作,例如:

SELECT i.*  -- or whatever you need
FROM   instructor_student i
JOIN  (
   SELECT ...  -- query from above
   ) f ON f.instructor_student_id = i.id
;