MySQL/GROUP BY

来自康健生活
Kangkk​(留言 | 贡献)2026年1月19日 (一) 13:49的版本 (Kangkk移动页面Mysql/GROUP BY至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