Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/53.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.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 ActiveRecord选择帐户中有3列的不同记录_Mysql_Ruby On Rails_Sqlite_Activerecord - Fatal编程技术网

Mysql ActiveRecord选择帐户中有3列的不同记录

Mysql ActiveRecord选择帐户中有3列的不同记录,mysql,ruby-on-rails,sqlite,activerecord,Mysql,Ruby On Rails,Sqlite,Activerecord,在以下场景中: 课时(教师id、房间id、课时id、小组id、科目id) 我需要获得给定教师的所有课时,而不需要考虑组id id teacher_id room_id hour_id group_id subject_id 1 1 1 1 1 1 2 1 1 1 2 1 3

在以下场景中:

课时(教师id、房间id、课时id、小组id、科目id)

我需要获得给定教师的所有课时,而不需要考虑组id

id    teacher_id    room_id    hour_id    group_id    subject_id
1         1            1          1          1            1
2         1            1          1          2            1
3         1            2          2          1            1
4         2            1          3          2            3
我只需要获取给定教师的房间id、小时id和科目id的
唯一记录

这是:
teacher\u one.时间表
应该返回id为[1,3]的
课时
,因为id=2的课时不唯一

简而言之:如果我的老师有id
1
teacher.schedule
需要返回:

id    teacher_id    room_id    hour_id    group_id    subject_id
1         1            1          1          1            1
3         1            2          2          1            1

在一次黑客会议之后,我们以以下内容结束,这完全有效:

class Teacher
  ...
  def schedule
    ids = ClassHour.find_by_sql(['SELECT max(class_hours.id) mid FROM class_hours inner join hours on class_hours.hour_id = hours.id inner join rooms on class_hours.room_id = rooms.id where class_hours.teacher_id = ? group by hours.id, rooms.id', self.id]).map { |x| x['mid'] }
    ClassHour.find ids
  end
end

但我不完全理解为什么这个查询能像我所希望的那样工作。如果有人能解释一下,那就太好了。

在一次黑客会议之后,我们以以下内容结束,这完全有效:

class Teacher
  ...
  def schedule
    ids = ClassHour.find_by_sql(['SELECT max(class_hours.id) mid FROM class_hours inner join hours on class_hours.hour_id = hours.id inner join rooms on class_hours.room_id = rooms.id where class_hours.teacher_id = ? group by hours.id, rooms.id', self.id]).map { |x| x['mid'] }
    ClassHour.find ids
  end
end

但我不完全理解为什么这个查询能像我所希望的那样工作。如果有人能解释,那就太好了。

添加了期望的结果,@Strawberry添加了期望的结果,@Strawberry