我试图在ruby on rails上执行以下操作,但即使我可以在mysql中得到一个很棒的答案。
我有学生和课程表。学生 - >课程是一对多的关系。
Student Course |--------------| |--------------------------------------| |id| name | |id | course_name | grade | student_id | |---------- | |--------------------------------------| |S1| student 1 | |C1 | Course1 | A | S1 | |S2| student 2 | |C2 | Course2 | C | S1 | |---------- | |C3 | Course1 | A | S2 | |C4 | Course2 | B | S2 | |--------------------------------------|
select * from Student
where id NOT IN (select student_id from Course where grade = 'C')
我希望使用单个SQL JOIN语句或使用activerecord来实现相同的结果。
答案 0 :(得分:1)
SELECT * FROM Student s
LEFT JOIN Course c ON s.id=c.student_id AND c.grade = 'C'
WHERE c.student_id IS NULL;
或加入您的子查询
SELECT * FROM Student s
LEFT JOIN (SELECT student_id FROM Course WHERE grade = 'C') c
WHERE c.student_id IS NULL;
或使用存在
SELECT * FROM Student s
WHERE NOT EXISTS (SELECT NULL FROM Course WHERE grade = 'C' AND student_id=s.id);
我恐怕此刻无法测试,我怀疑这些查询可能无法帮助您。我没有使用ActiveRecord的经验。请在评论中告诉我。
答案 1 :(得分:0)
预言:
select distinct s.* from student s left join course c on c.student_id=s.id where c.grade!='c'
Student.all(:select=>"distinct student.*",:joins=>"left join course on course.student_id=student.id",:conditions=>"course.grade!='c'")