查找字符串的顺序

时间:2016-04-18 14:09:34

标签: mysql sql

我想通过下面的代码找到1列中的所有序号。 有问题导致col1有类型字符串,所以我不能做任何数学计算。 有没有人解决这个问题?

select t.*
    from t
    where exists (select 1
                  from t t2
                  where t2.col1 in (t.col1 - 1, t.col1 + 1)
                 );

1 个答案:

答案 0 :(得分:0)

您可以使用min()和max()或排序和限制1来确定给定值旁边的值。从起点开始,值不一定是+ 1 / -1,因为值可能会丢失,或者id的文本部分可能会发生变化。如果您要在一组记录中查找此类值,则最小值/最大值会更好。

对于所有col1值:

select t1.col1, max(t2.col1), min(t3.col1)
from t t1
left join t t2 on t1.col1>t2.col1
left join t t3 on t1.com1<t2.col1
group by t1.col1

您可以加入表格t 2x以获取t中其他col1值的数据。

对于特定的col1值:

select * from t where col1>'specific value' order by col1 asc limit 1
union
select * from t where col1<'specific value' order by col1 desc limit 1