我的表格如下所示:
col1 | col2 | col3
-----+------+-------
1 | a | 0
2 | b | 0
3 | c | 1
4 | a | 1
5 | a | 0
我的要求是:
1. find all records from the table where col2 = 'a'
2. For those results whose col3 = 1, ALSO find their previous record whose col3 is not 1
前面的记录是指 col1 中的数字序列。例如,对于col1=5的记录,其前一条记录是col1=4的记录
如何在 MYSQL 查询中完成此操作?
最佳答案
如果您的 col1 列上没有间隙,一种可能的解决方案可能如下所示:
select
*
from
tablename
where
col1 in (select col1 from tablename where col2='a'
union all
select col1-1 from tablename where col2='a' and col3='1')
关于mysql - 如果一条记录满足 MYSQL 查询中的检查,则查找另一条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34543089/