【问题标题】:How to write this MySQL join query?如何编写这个 MySQL 连接查询?
【发布时间】:2014-07-27 20:35:38
【问题描述】:

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

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

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

每个问题都属于一个作业。我可以使用问题表中的 assignment_id 检索作业的所有问题。

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

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

【问题讨论】:

  • 最终最好成绩是什么意思?
  • 我认为他指的是作业成绩最好的学生。
  • 一个学生可能对作业中的同一个问题有多个答案。我想从这些尝试中获得最好的成绩。如果同一个人对同一问题的两个答案具有相同的分数但时间戳不同,则最终的最佳分数是较早的一个。我希望这很清楚:)

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


【解决方案1】:

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

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 参数。

【讨论】:

  • 嘿,您的代码检索最高分,而与解决方案 ID 无关。我的意思是,如果同一个人多次尝试,它会从同一个人的另一个解决方案中检索最高分。
  • @ChrisL,如果要添加字段,则应该更新组。
【解决方案2】:

考虑这些关系:

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

【讨论】:

    猜你喜欢
    • 2012-02-03
    • 1970-01-01
    • 2011-09-13
    • 1970-01-01
    • 2015-08-03
    • 2017-01-12
    • 2015-10-19
    • 1970-01-01
    相关资源
    最近更新 更多