【问题标题】:Rails: Conditional subquery MAX(effective_date)Rails:条件子查询 MAX(effective_date)
【发布时间】:2021-01-27 14:02:47
【问题描述】:

假设,数据库中有三张表:

课程(:id, :name)

course_details(:course_id, :effective_date, :status),

course_codes(:course_detail_id, :code)

课程有很多 course_details

course_detail 有很多课程代码

课程可以有多个 course_details 记录,这些记录是有效日期的(意味着系统中只会使用一个 course_detail 记录)。

问题说明:我想通过给定代码的课程代码过滤课程。并且课程应该只被与有效日期 course_detail 链接的 course_codes 过滤,并且应该跳过过去的有效日期记录。

course = Course.find(params[:id])

course_detail = CourseDetail.find_by(effective_date: CourseDetail.max(effective_date), course_id: course.id)

如果我使用此代码,这将过滤课程,而不考虑有效日期的课程详细信息:

Course.left_joins(course_details: :course_codes).where(course_details: { course_codes: { code: params[:code] } })

课程:

Id Name
1 English
2 Maths

课程详情:

id course_id effective_date
1 1 2020-10-01
2 1 2021-01-01
3 2 2020-09-01

课程代码:

id course_detail_id code.
1 1 eng-01
2 2 eng-505
3 3 math-01

当我通过 code = eng-01 时,它应该返回空数组,而不是 id 1。

有人可以帮帮我吗?

【问题讨论】:

  • 您能否提供数据样本和预期结果?
  • @max 示例数据已添加。

标签: ruby-on-rails ruby postgresql subquery ruby-on-rails-6.1


【解决方案1】:

为了解决这个问题,我使用了一个子查询,它根据有效日期返回所有课程的 course_details 的 ID:

    query = "select child.id from courses as parent
  inner join course_details as child on child.course_id = parent.id
  where child.effective_date = 
  (select  max(child1.effective_date) as effective_date
  from    course_details as child1
  where   child1.course_id = parent.id
  and (child1.effective_date <= CURRENT_DATE
    or child1.effective_date = (select  min(child2.effective_date) as effective_date
    from    course_details as child2
    where   child2.course_id = parent.id)
    ))"
effective_dated_ids = Course.find_by_sql(query).pluck(:id)

得到所有的id后,我在搜索中传递了这些id。

records = Course.left_joins(course_details: :course_codes).where(course_details: { id: effective_record_ids, course_codes: { course_code: params[:course_code] } })

它按预期工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多