MySql基于其他行选择行

时间:2019-09-16 10:25:51

标签: mysql greatest-n-per-group

这是我从df1.join(df2,df1.NAME == df2.NAME,"left")MySQL中获得的当前结果

tbl_msresponse

从上面我想要

MobileNo         Time                     Status
xxxxx69333       2019-09-15 13:11:54      FAILED 
xxxxx69333       2019-09-15 14:12:16      FAILED
xxxxx69333       2019-09-15 14:21:34      DELIVERED **<- this row required**
xxxxx88779       2019-09-15 13:11:54      FAILED **<- this row required**
xxxxx76555       2019-09-15 14:12:16      FAILED
xxxxx76555       2019-09-15 14:21:34      DELIVERED **<- this row required**

所以,现在我只想要 MobileNo Time Status xxxxx69333 2019-09-15 14:21:34 DELIVERED xxxxx88779 2019-09-15 13:11:54 FAILED xxxxx76555 2019-09-15 14:21:34 DELIVERED 行。如果没有DELIVERED行,我只想根据DELIVERED列显示FAILED的最后MobileNo行。如何在Time中做到这一点?

3 个答案:

答案 0 :(得分:0)

您可以使用limit取1个结果,如果要使用last,则需要使用DESC关键字,否则ASC可以这样编写:

Select * from table_name where Status="Delivered" or Status = Select status from table_name where Status="Failed" order by Time DESC LIMIT 1;

答案 1 :(得分:0)

如果您要使用存储过程,那么这是我使用存储过程的解决方案。实际上,您可以在存储过程中编写if/else条件。该条件基本上检查是否存在状态为DELIVERED的行,然后返回所有行,否则按时间返回FAILED状态行顺序,限制为1。

这是程序:

DELIMITER //
create procedure my_procedure()
begin
    IF NOT EXISTS (SELECT * FROM my_response where status='DELIVERED')
    THEN
        SELECT * from tbl_msresponse WHERE Status='FAILED' order by Time DESC LIMIT 1;
    ELSE
        SELECT * from tbl_msresponse WHERE Status='DELIVERED';
    END IF;
end //
DELIMITER;

您可以像下面这样调用此过程:

call my_procedure();

答案 2 :(得分:0)

假设状态为二进制(即失败或已交付),则与状态的讨论无关,您所需要的只是mobileno的最新条目

select t.*
from t 
where time = (select max(time) from t t1 where t1.mobileno = t.mobileno);

+----------+---------------------+-----------+
| MobileNo | Time                | Status    |
+----------+---------------------+-----------+
|    69333 | 2019-09-15 14:21:34 | DELIVERED |
|    88779 | 2019-09-15 13:11:54 | FAILED    |
|    76555 | 2019-09-15 14:21:34 | DELIVERED |
+----------+---------------------+-----------+
3 rows in set (0.00 sec)