如何在特定条件下从表中获取最接近的记录

时间:2018-05-02 12:20:07

标签: mysql

我有一张如下表格。

Name            flag
--------------------------------
ABC             success
DEF             fail
GHI             success
JKL             fail
MNO             fail
PQR             fail
STU             fail

我必须在下面的记录中获得成功" flag record。我已经尝试了几次,但我是mysql的新手。

我的记录应该是: -

Name            flag
--------------------------------
JKL             fail

3 个答案:

答案 0 :(得分:2)

1)我考虑了'id'列来考虑下一条记录

  select * from yourtable where id = (select id from yourtable where flag='success')+1

2)我也考虑过使用rownum

CREATE TABLE yourtable
    (`Name` varchar(3), `flag` varchar(7))
;

INSERT INTO yourtable
    (`Name`, `flag`)
VALUES
    ('ABC', 'fail'),
    ('DEF', 'fail'),
    ('GHI', 'success'),
    ('JKL', 'fail'),
    ('MNO', 'fail'),
    ('PQR', 'fail'),
    ('STU', 'fail')
;

create temporary  table t1 as 

select name,flag,@rownum:=@rownum+1 as rownum
from yourtable ,(SELECT @rownum := 0) as r;

select name,flag from t1 where rownum = 
(select rownum from t1 where flag='success')+1

点击此处 - http://sqlfiddle.com/#!9/cbd4b/5

答案 1 :(得分:0)

SELECT *
FROM [Table_1]
WHERE [Table_1].id > (SELECT [Table_1].id FROM [Table_1] WHERE flag = 'success')
LIMIT 1

应该在旗帜"成功"

之后返回第一行

答案 2 :(得分:0)

如果您有兴趣使用Windows功能。

选择*,引导(标记,成功)(按名称排序)作为next_comm 来自yourtable;