我有下表
Id | Status | date
-------------------
1 | Onsite |2007
2 | Onsite |2008
3 | Onsite |2009
4 | Abroad |2010
5 | Abroad |2011
6 | Onsite |2012
7 | Abroad |2013
8 | Abroad |2014
9 | Onsite |2015
我想要MySQL中的查询,当状态从“国外”更改为“现场”时,该查询返回一条记录。
在上述情况下,查询将返回以下行:
6 | Onsite |2012
9 | Onsite |2015
最佳答案
请尝试以下查询,即使id不在序列中,该查询也可以使用:
SELECT *
FROM 'table_name' t
WHERE t.status = 'Onsite' and
EXISTS(SELECT t1.id
FROM 'table_name' t1
WHERE t1.status = 'Abroad' and t1.id<t.id
ORDER BY t1.id DESC
LIMIT 1,1);