mysql - 查找字符串的顺序

标签 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)
                 );

最佳答案

您可以使用 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

您可以加入 2 倍以上的表 t 以从 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

关于mysql - 查找字符串的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36696399/

相关文章:

mysql - 在其他条件行之后查找特定条件行

SQL:如何从单个列中选择满足多个条件的单个 id ("row")

javascript - Jquery Ajax 无法获取当前聚焦的输入元素

php - 从数据库中选择时的隐藏字段更改

mysql - 选择特定列数据的多次出现

.net - 最快的 .Net 和 SQL 数据类型

mysql - 'where clause' 中的未知列 - 在 WHERE 中使用 ALL 运算符时

php - 如何避免此 PDO 异常 : Cannot execute queries while other unbuffered queries are active

php - Mysql/php 选择顺序

mysql - 选择 subselect 返回多个值的行