左连接SQL表并获取最近一行的值

时间:2017-05-29 19:26:24

标签: mysql sql

我现在已经处理了一段时间的SQL语句。

如何从另一个表中获取最新(按日期,然后是id)权重值。这是我到目前为止的查询:

SELECT e.name, e.picture_url, e.id AS exercise_id, w.parent_id, e.video_url,
        w.id, w.comment, w.time, w.reps, w.rest, w.sets, wt.name as wtype,
        w.order_by, mg.name as muscle_group, eq.name as equipment, w_track.*
        FROM workout w
        LEFT JOIN exercises e
        ON e.id = w.exercise_id
        LEFT JOIN workout_types wt
        ON wt.id = e.workout_type_id
        LEFT JOIN muscle_groups mg
        ON e.muscle_group_id = mg.id
        LEFT JOIN equipments eq
        ON eq.id = e.equipment_id

        LEFT JOIN (SELECT workout_id, weight FROM workout_tracking GROUP BY workout_id ORDER BY date DESC, id DESC) w_track
        ON w.id = w_track.workout_id


        WHERE workout_day_id = 395

我想离开join workout_tracking并获取最新的'weight'值 - 具有最新日期和最高ID的行。

提前致谢! 所有帮助表示赞赏!

更新 当我运行上面的查询时,我得到一些随机的“权重”数字,而不是最近的数字。

'exercise'表格包括: - id(workout_tracking的主键) - workout_day_id('workout_day'的外键 - 代表 - 休息 - 套 - 等......

'workout_tracking'表格包括: - ID - workout_id(锻炼表外键) - 重量 - 日期

示例数据 “workout'表:

  +---+------------+-------------+
  |id |     sets   |    reps     |
  +---+------------+-------------+
  | 1 |      3     |     10

“workout_tracking'表:

  +---+------------+-------------+-------------+
  |id | workout_id |    weight   |    date
  +---+------------+-------------+-------------+
  | 1 |      1     |     10        2017-05-22
    2        1           12        2017-05-28
    3        1           14        2017-05-28
    4        1           11        2017-05-28
    5        1          NULL       2017-05-28
    6        1          NULL       2017-05-28

2 个答案:

答案 0 :(得分:1)

简单的方法是使用变量:

SQL DEMO

SELECT `id`, `workout_id`, `weight`, `date`,
       @rn := IF( @workout_id = `workout_id`,
                  @rn + 1,
                  IF(@workout_id := `workout_id`, 1, 1)
                ) as rn
FROM workout_tracking     
CROSS JOIN (SELECT @rn := 0, @workout_id := -1) as var
ORDER BY `workout_id`, `date` DESC, `id` DESC

因为您首先为workout_id订购,所以您可以找到最新的date和最新的id,在这种情况下,这些会有@rn = 1

现在你的最终查询应该是

SELECT w.*, filter.*
FROM workout w
JOIN (SELECT `id`, `workout_id`, `weight`, `date`,
              @rn := IF( @workout_id = `workout_id`,
                         @rn + 1,
                         IF(@workout_id := `workout_id`, 1, 1)
                       ) as rn
      FROM workout_tracking     
      CROSS JOIN (SELECT @rn := 0, @workout_id := -1) as var
      ORDER BY `workout_id`, `date` DESC, `id` DESC
     ) as filter
 ON w.id = filter.`workout_id`
WHERE filter.rn = 1;

LEFT JOIN尝试:

LEFT JOIN ( ... ) as filter
  ON w.id = filter.`workout_id`
 AND filter.rn = 1

不需要where条件。

答案 1 :(得分:0)

LEFT JOIN(SELECT MAX(workout_id)AS workout_id,weight FROM workout_tracking GROUP BY workout_id ORDER BY date DESC,id DESC)w_track ON w.id = w_track.workout_id