这是关系部门的一种情况。
实际的表定义(标准的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_idFROM feesWHERe course_type = ?AND monthly_detail = ANY(ARRAY[?]::date[]) -- ANY, not ALL!GROUP BY instructor_student_idHAVINg count(*) = cardinality(ARRAY[?]::date[]);
假设您的数组中有 不同的
值,并且表中的费用是唯一的条目,就像
UNIQUE我上面添加的约束所强制执行的那样。否则,计数是不可靠的,您必须使用更复杂的查询。这是一个选项库:
- 如何筛选具有多次通过关系的SQL结果
如您所见,我根本没有涉及该表
instructor_student。虽然参照完整性是通过FK约束来强制执行的(通常如此),但我们可以
fees单独使用它来确定资格
instructor_student_id。如果您需要从主表中获取更多属性,请在第二步中进行操作,例如:
SELECt i.* -- or whatever you needFROM instructor_student iJOIN ( SELECt ... -- query from above ) f ON f.instructor_student_id = i.id;



