开发者

How can I ignore a row from a table if one of it's associated table's column fail to meet the condition?

开发者 https://www.devze.com 2023-03-05 19:11 出处:网络
I am trying to do the following in ruby on rails, but even if I can get an answer in mysql that would be great.

I am trying to do the following in ruby on rails, but even if I can get an answer in mysql that would be great.

I have tables Student and Courses. S开发者_Go百科tudent -> Courses is one-to-many relationship.

  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')

I want to achieve same result using single SQL JOIN statement or using activerecord.


SELECT * FROM Student s 
LEFT JOIN Course c ON s.id=c.student_id AND c.grade = 'C' 
WHERE c.student_id IS NULL;

Or join to your subquery

SELECT * FROM Student s 
LEFT JOIN (SELECT student_id FROM Course WHERE grade = 'C') c
WHERE c.student_id IS NULL;

Or use exists

SELECT * FROM Student s 
WHERE NOT EXISTS (SELECT NULL FROM Course WHERE grade = 'C' AND student_id=s.id);

I'm afraid I can't test this at the moment and I have a suspicion that these queries may not help you. I have no experience with ActiveRecord. Let me know in the comments.


oracle:

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'")
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号