MySQL/GROUP BY

来自康健生活

标题文字

场景是根据团队id和用户id进行排序,然后取其中团队id和用户id相同但create_at时间最大的条目。

SELECT
  MAX(tmp.create_at) AS create_at,
  tmp.team_id,
  tmp._user_id
FROM 
  (
    SELECT
      thf.team_id AS team_id,
      thf.user_id AS user_id,
      thf.message -> '$.user' AS _user_id,
      thf.create_at AS create_at
    FROM
      md_team_history thf 
    WHERE
      thf.message -> '$.user' IS NOT NULL
  ) AS tmp
GROUP BY
  tmp.team_id,
  tmp._user_id
ORDER BY
  tmp.team_id,
  tmp._user_id