这是我的 table :
id Name salary
------------------------------------
B101 mob 10000
B1000 John 1000000
B1002 flip 10000
B1030 Bean 100000
这是我的查询:
Select * from table
where table.id >= 'B1000' and
table.id <= 'B1050'
这是我期待的结果:
id Name salary
------------------------------------
B1000 John 1000000
B1002 flip 10000
B1030 Bean 100000
这就是我得到的:
id Name salary
------------------------------------
B1000 John 1000000
B101 mob 10000
B1002 flip 10000
B1030 Bean 100000
怎样才能得到预期的结果?
最佳答案
如果列 id 始终以 B(或其他字符)开头,后跟数字,那么您可以尝试以下操作:
Select * from table
where substr(table.id,2,length(table.id) - 1) >= 1000
and substr(table.id,2,length(table.id) - 1) <= 1050
说明:
假设您有这样的示例数据:
id
---------
A67
B32132
C89163
此查询:
select substr(table.id,2,length(table.id) - 1) as id from table
会产生:
id
----------
67
32132
89163
..substr(table.id,2...
中的 2 表示从列 id 中的字符 2 开始。
如果列 ID 包含多个字符(比方说 3 个字符),例如
id
-----------
Azx67
Byx32132
Czx89163
您需要此查询:
select substr(table.id,4,length(table.id) - 3) as id from table
生产
id
-------------
67
32132
89163
..substr(table.id,4...
中的 4 表示从列 id 中的字符 4 开始。
请注意,该列应该有一个模式。如果样本数据如下:
id
--------
A123
BB123
CCC23
您需要更复杂的查询才能获得所需的结果。实际上,不建议这样填写 id 列。
您可以将其添加到 where 子句中,例如:
Select * from table
where substr(table.id,3,length(table.id) - 2) >= 1000 --start from characters 3 in column id
and substr(table.id,3,length(table.id) - 2) <= 1050 --start from characters 3 in column id
关于mysql - MySQL 中 VARCHAR 的 Between 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34849842/