在 MySQL 中使用 GROUP BY 选择最近的行

Select most recent row with GROUP BY in MySQL(在 MySQL 中使用 GROUP BY 选择最近的行)
本文介绍了在 MySQL 中使用 GROUP BY 选择最近的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试选择每个用户最近一次付款.我现在的查询选择用户第一次付款.IE.如果用户进行了两次付款并且 payment.ids 是 10 和 11,则查询将选择具有付款 ID 信息的用户,而不是 11.

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 payment.ids are 10 and 11, the query selects the user with the info for payment id 10, not 11.

  SELECT users.*, payments.method, payments.id AS payment_id 
    FROM `users` 
         LEFT JOIN `payments` ON users.id = payments.user_id 
GROUP BY users.id

我添加了 ORDER BY payment.id,但查询似乎忽略了它,仍然选择第一笔付款.

I've added ORDER BY payments.id, but the query seems to ignore it and still selects the first payment.

感谢所有帮助.谢谢.

推荐答案

您想要 分组最大值;本质上,将支付表分组以识别最大记录,然后将结果与自身连接以获取其他列:

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

请注意,MAX(id) 可能不是最近的付款",具体取决于您的应用程序和架构:通常最好确定最最近"基于 TIMESTAMP 而不是基于合成标识符,例如 AUTO_INCREMENT 主键列.

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.

这篇关于在 MySQL 中使用 GROUP BY 选择最近的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)