简体   繁体   English

选择每个用户的最后一个条目

[英]SELECT last entry for each user

I have a TABLE user_orders with fields --> 我有一个带有字段的TABLE user_orders->

  • order_id int(10), order_id int(10),
  • user_id int(10), user_id int(10),
  • order_payment_id int(10) order_payment_id int(10)
  • order_created int(10) order_created int(10)

I want to find the last order_payment_id used for each user_id. 我想找到每个用户ID使用的最后一个order_payment_id。 I try 我尝试

SELECT order_payment_id, user_id , MAX(order_id) as lastone
FROM user_orders 
GROUP BY user_id;

but the result is wrong 但结果是错误的

You can use a self-join to filter out the relevant data 您可以使用自联接过滤掉相关数据

SELECT o1.*
FROM user_orders o1
JOIN
(
   SELECT user_id, MAX(order_created) as lastone 
   FROM user_orders
   GROUP BY user_id
) o2 on o1.user_id = o2.user_id 
    and o1.order_created = o2.lastone
GROUP BY o1.user_id

The MAX should be in the WHERE clause, or it will select the maximum order_id for the whole table. MAX应该在WHERE子句中,否则它将为整个表选择最大的order_id

SELECT order_payment_id, user_id ,order_id as lastone
FROM user_orders u1
WHERE  u1.order_id = (SELECT MAX(order_id)
                      FROM user_orders u2
                      WHERE u1.user_id = u2.user_id);

Using this query, you can get rid of the GROUP BY except if order_id is not unique. 使用此查询,您可以摆脱GROUP BY除非order_id不是唯一的。

That way you'll get the last order associated with the user. 这样,您将获得与用户关联的最后一个订单。

The general GROUP BY rule is: If a GROUP BY clause is specified, each column reference in the SELECT list must either identify a grouping column or be the argument of a set function. 一般的GROUP BY规则是: 如果指定了GROUP BY子句,则SELECT列表中的每个列引用都必须标识一个分组列或作为set函数的参数。

SELECT order_payment_id, user_id , order_id as lastone
FROM user_orders uo
WHERE order_id = (select MAX(order_id) from user_orders
                  where user_id = uo.user_id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM