Turn SQL query into ActiveRecord Relation

前端 未结 1 1796
温柔的废话
温柔的废话 2021-02-14 01:10

How can I turn the following SQL query into an ActiveRecord relation so that I can expand on it with scopes?

WITH joined_table AS (
    SELECT workout_sets.weigh         


        
相关标签:
1条回答
  • 2021-02-14 01:49

    You are apparently trying to get the latest workout (highest id) details that match the highest weight for each user. It also appears that you are using PostgreSQL (MySQL doesn't have CTE's), correct me if I'm wrong on this.

    If so, you can make use of windowing functions and simplify your query to:

    SELECT * FROM (
      SELECT workouts.*, workout_sets.weight,
                         workout_sets.id AS workout_set_id,
                         workout_exercises.id AS exercise_id,
                         ROW_NUMBER() OVER (
                             PARTITION BY workouts.user_id 
                             ORDER BY workout_sets.weight DESC, workouts.id DESC ) as rowNum
      FROM workouts
      JOIN workout_exercises ON workout_exercises.workout_id = workouts.id 
      JOIN workout_sets ON workout_sets.workout_exercise_id = workout_exercises.id
    ) t
    WHERE rowNum = 1
    

    Which in ActiveRecord can be written as:

    selected_fields = <<-SELECT
      workouts.*, 
      workout_sets.weight,
      workout_sets.id AS workout_set_id,
      workout_exercises.id AS exercise_id,
      ROW_NUMBER() OVER (
         PARTITION BY workouts.user_id 
         ORDER BY workout_sets.weight DESC, workouts.id DESC) as rowNum
    SELECT
    
    subquery = Workout.joins(:workout_exercises => :workout_sets).
                       select(selected_fields).to_sql
    Workout.select("*").from(Arel.sql("(#{subquery}) as t"))
           .where("rowNum = 1")
    
    0 讨论(0)
提交回复
热议问题