如何编写这个MySQL连接查询?

时间:2014-06-06 14:21:48

标签: mysql sql ruby-on-rails database join

我需要为以下场景编写MySQL连接查询。

  • 我有一个答案表,其中包含id,score,student_id,tests_passed,created_at,problem_id。
  • 我有一个问题表,它有一个id,assignment_id。
  • 我有一个作业表,它有一个id,title和其他字段。

每个答案都属于一个问题。在答案表中,我可以使用problem_id检索问题的所有答案。

每个问题都属于一项任务。我可以使用问题表中的assignment_id来检索赋值的所有问题。

我需要检索学生在作业中的最终最高分。

有没有办法在不使用多个查询的情况下实现这一目标。

2 个答案:

答案 0 :(得分:0)

考虑到这些关系:

class Answer < ActiveRecord::Base
  belongs_to :student
  belongs_to :problem

class Problem < ActiveRecord::Base
  belongs_to :assignment
  has_many :answers

class Assignment < ActiveRecord::Base
  has_many :problems # or has_one, whatever

class Student < ActiveRecord::Base
  has_many :answers
  has_many :problems, through: :answers # You might not have this relation configured

你可以这样做:

scope = Student.includes(answers: { problems: :assignment })
scope = scope.where(problems: { title: '3x + 2 = 12' })
scope = scope.where(students: { name: 'Johnny' })
scope = scope.where(assignment: { id: my_assignment_id })
scope = scope.select('MAX(score), *') # not sure about this part, depending on your needs

答案 1 :(得分:0)

要查看给定作业/问题的所有学生最佳作业分数,这应该有效:

select student_id, problem_id, assignment_id, max(score)  from answers 
join problem on answers.problem_id = problem.id
join assignments on problem.assignment_id = assignments.id
where assignment_id = <your assignment param>
and problem_id = <your problem param>
and answers.id = <your answers id>
group by student_id

但是,如果单个作业的问题是唯一的,那么你应该能够取消使用assignment_id参数。