Select most recent row with GROUP BY in MySQL

后端 未结 6 2021
爱一瞬间的悲伤
爱一瞬间的悲伤 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:56

    I've just been dealing with pretty much exactly the same problem and found these answers helpful. My testing seems to suggest you can make it slightly simpler than the accepted answer, viz.:

    SELECT u.*, p.method, p.id AS payment_id 
    FROM `users` u, `payments` p
    WHERE u.id = p.user_id 
        AND p.id = (SELECT MAX(p2.id) FROM payments p2
                        WHERE p2.user_id = u.id);
    

    I've not performance tested the differences but the db I'm working on has over 50,000 Users and over 60,000 payments and the query runs in 0.024 seconds.

提交回复
热议问题