Select most recent row with GROUP BY in MySQL

后端 未结 6 2030
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-09 03:26

I\'m trying to select each user with their most recent payment. The query I have now selects the users first payment. I.e. if a user has made two payments and the paym

6条回答
  •  半阙折子戏
    2020-12-09 03:45

    You want the groupwise maximum; in essence, group the payments table to identify the maximal records, then join the result back with itself to fetch the other columns:

    SELECT users.*, payments.method, payments.id AS payment_id
    FROM   payments NATURAL JOIN (
      SELECT   user_id, MAX(id) AS id 
      FROM     payments
      GROUP BY user_id
    ) t RIGHT JOIN users ON users.id = t.user_id
    

    Note that MAX(id) may not be the "most recent payment", depending on your application and schema: it's usually better to determine "most recent" based off TIMESTAMP than based off synthetic identifiers such as an AUTO_INCREMENT primary key column.

提交回复
热议问题