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

标签 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

我想要实现的是获取针对每个成员(member)的客户不成功的最后订单

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

到现在为止,我已经使用了这个查询,但它返回不成功记录的最大值并且不服从最后一条记录。

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

这里是查询

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

最佳答案

如果最后你的意思是最后一个,那么你可以使用 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 .

如果您希望每位客户成为成员(member):

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            |

关于MySQL - 根据条件获取每个成员的最后记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57292125/

相关文章:

MySQL - 如何查询涉及前面计算值的表结果

mysql - 如何在 MS SQL Server Management 2005 中将列信息合并为一行

php - 使用 css 在 php/styling 中分配类

mysql - SQL多表连接 throw 欺骗

sql - Oracle - 仅从列中选择最大值

mysql - 获取 MySQL 表中的行位置

mysql - 增加 Mysql 数据库中的表数

php - MySql/php 中的换行符

sql - 如何在连接查询中合并两列?

MySQL 嵌套选择查询性能