MySQL-根据条件获取每个成员资格的最新记录

时间:2019-07-31 13:37:15

标签: mysql sql

查询时需要帮助:

Table Customers
id        name       email
1         john       john@abc.com
2         doe        doe@abc.com

Table Membership
id      facility       package
1       a              x
2       b              y
3       c              z

Table Orders
id      orderid        result            customerid      membershipid
1       order-1        Unsuccessful      1               1
2       order-2        Successful        2               1
3       order-3        Successful        1               1
4       order-4        Successful        1               2
5       order-5        Unsuccessful      1               2

我想要实现的是获得每个会员的客户都无法获得的最后订单

这意味着在这种情况下,查询应仅返回order-5。因为membershipid 1的最后一条记录成功。

到目前为止,我已经使用了此查询,但是它返回的最大记录失败,并且不遵循最后一条记录。

我希望我已经解释了我的问题。

这是查询

SELECT o.transactionresult FROM orders o where o.transactionresult='Unsuccessful' group by o.membershipid ORDER by o.id DESC

2 个答案:

答案 0 :(得分:2)

如果最后一个表示您的ID,那么您可以使用NOT EXISTS:

SELECT o.* 
FROM orders o 
where o.transactionresult='Unsuccessful'
and not exists (
  select 1 from orders
  where membershipid = o.membershipid and id > o.id
)

请参见demo

如果您希望获得每个客户的会员资格:

SELECT o.* 
FROM orders o 
where o.transactionresult='Unsuccessful'
and not exists (
  select 1 from orders
  where membershipid = o.membershipid and customerid = o.customerid and id > o.id
)

请参见demo
结果:

| id  | orderid | transactionresult | customerid | membershipid |
| --- | ------- | ----------------- | ---------- | ------------ |
| 5   | order-5 | Unsuccessful      | 1          | 2            |

答案 1 :(得分:1)

您可以为此使用聚合:

select o.customer, o.membership, max(o.id)
from orders o
group by o.customer, o.membership
having max(o.id) = max(case when o.result = 'Unsuccessful' then o.id end);

这将返回客户/成员身份组合,其中最大id是不成功的最大id。

如果想要整行,我将使用相关的子查询:

select o.*
from orders o
where o.result = 'Unsuccessful' and
      o.id = (select max(o2.id)
              from orders o2
              where o2.customer = o.customer and o2.membership = o.membership
             );

这将检查结果是否成功,并且该id是客户/会员组合的最大id。