我有一张表 courses
和一张表 volunteer_rosters
。 courses
包含所有类(class)的列表,volunteer_rosters
包含教授/协助类(class)的志愿者列表。
我想编写一个查询,返回所有没有分配有志愿者的类(class)列表。这是正在发生的事情:
courses
-------
id
1
3
4
5
6
volunteer_courses
-----------------
id 1 course_id 1
id 2 course_id 1
id 3 course_id 1
id 5 course_id 3
id 6 course_id 3
以下所有查询均返回
course_id 3
类(class)编号 4
类(class)编号 5
为什么 course_id 1(正确)被排除在外,但 course_id 3 却没有???
Course.joins("LEFT JOIN student_rosters ON courses.id = student_rosters.course_id where student_rosters.course_id is null")
Course.joins("LEFT JOIN student_rosters ON courses.id = student_rosters.course_id").where(student_rosters: {id: nil})
Course.includes(:student_rosters).references(:student_rosters).where(student_rosters: {id: nil})
Course.includes(:student_rosters).references(:student_rosters).where('student_rosters.id = ?', nil)
Course.joins("LEFT JOIN student_rosters ON courses.id = student_rosters.course_id").where(student_rosters: {id: nil})
同样的问题,但没有一个解决方案对我有用:
最佳答案
不需要使用join
。试试这个:
select id from Courses
where id not in (select course_id from volunteer_courses)
关于mysql - 左连接没有返回正确的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50549778/