Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如果表中有一行';s关联表';s列不符合条件?_Mysql_Sql_Ruby On Rails_Activerecord - Fatal编程技术网

Mysql 如果表中有一行';s关联表';s列不符合条件?

Mysql 如果表中有一行';s关联表';s列不符合条件?,mysql,sql,ruby-on-rails,activerecord,Mysql,Sql,Ruby On Rails,Activerecord,我试图在RubyonRails中完成以下工作,但即使我能在mysql中得到答案,那也太好了 我有学生桌和课程。学生->课程是一对多关系 Student Course |--------------| |--------------------------------------| |id| name | |id | course_name | grade | student_id | |---------- | |-------

我试图在RubyonRails中完成以下工作,但即使我能在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 | |--------------------------------------| 我希望使用单个SQL JOIN语句或使用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;
或者加入子查询

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的经验。请在评论中告诉我。

oracle:



第一条SQL语句成功了。我无法理解为什么在where条件下使用“IS NULL”。您能详细说明一下吗?@chetu:左连接确保结果中表示左侧表(学生)中的所有行,即使右侧表(课程)中没有相应的行。在没有任何“真实”数据的情况下,右边的列为空。在这个查询中,他们是我们想要的学生。。。当按成绩='C'筛选时,课程表中未显示的课程。
SELECT * FROM Student s 
WHERE NOT EXISTS (SELECT NULL FROM Course WHERE grade = 'C' AND student_id=s.id);
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'")