是否有一种方法来检测一个值在MySQL查询中是否是一个数字?如
SELECT *
FROM myTable
WHERE isANumber(col1) = true
是否有一种方法来检测一个值在MySQL查询中是否是一个数字?如
SELECT *
FROM myTable
WHERE isANumber(col1) = true
当前回答
SELECT * FROM myTable
WHERE col1 REGEXP '^[+-]?[0-9]*([0-9]\\.|[0-9]|\\.[0-9])[0-9]*(e[+-]?[0-9]+)?$'
也会匹配带符号的小数(如-1.2,+0.2,6。, 2e9, 1.2e-10)。
测试:
drop table if exists myTable;
create table myTable (col1 varchar(50));
insert into myTable (col1)
values ('00.00'),('+1'),('.123'),('-.23e4'),('12.e-5'),('3.5e+6'),('a'),('e6'),('+e0');
select
col1,
col1 + 0 as casted,
col1 REGEXP '^[+-]?[0-9]*([0-9]\\.|[0-9]|\\.[0-9])[0-9]*(e[+-]?[0-9]+)?$' as isNumeric
from myTable;
结果:
col1 | casted | isNumeric
-------|---------|----------
00.00 | 0 | 1
+1 | 1 | 1
.123 | 0.123 | 1
-.23e4 | -2300 | 1
12.e-5 | 0.00012 | 1
3.5e+6 | 3500000 | 1
a | 0 | 0
e6 | 0 | 0
+e0 | 0 | 0
Demo
其他回答
您可以使用正则表达式的mor细节https://dev.mysql.com/doc/refman/8.0/en/regexp.html
我用这个^([,|.]?[0-9])+$。这个函数允许对小数和浮点数进行句柄处理
SELECT
*
FROM
mytable
WHERE
myTextField REGEXP "^([,|.]?[0-9])+$"
你也可以使用正则表达式…就像:
SELECT * FROM myTable WHERE col1 REGEXP '^[0-9]+$';
参考: http://dev.mysql.com/doc/refman/5.1/en/regexp.html
在我的计算机上,另一个似乎比REGEXP更快的替代方法是
SELECT * FROM myTable WHERE col1*0 != col1;
这将选择col1以数值开头的所有行。
如果你的数据是" test " " test0 " " test1111 " " 111test " " 111 "
选择所有数据类型为简单整型的记录:
SELECT *
FROM myTable
WHERE col1 REGEXP '^[0-9]+$';
结果:‘111’
(在正则表达式中,^表示开始,$表示结束)
使用实例选择存在整数或十进制数的所有记录。
SELECT *
FROM myTable
WHERE col1 REGEXP '^[0-9]+\\.?[0-9]*$'; - for 123.12
结果:'111'(与上一个示例相同)
最后,要选择number存在的所有记录,使用以下命令:
SELECT *
FROM myTable
WHERE col1 REGEXP '[0-9]+';
结果:'test0'和'test1111'和'111test'和'111'
SELECT * FROM myTable
WHERE col1 REGEXP '^[+-]?[0-9]*([0-9]\\.|[0-9]|\\.[0-9])[0-9]*(e[+-]?[0-9]+)?$'
也会匹配带符号的小数(如-1.2,+0.2,6。, 2e9, 1.2e-10)。
测试:
drop table if exists myTable;
create table myTable (col1 varchar(50));
insert into myTable (col1)
values ('00.00'),('+1'),('.123'),('-.23e4'),('12.e-5'),('3.5e+6'),('a'),('e6'),('+e0');
select
col1,
col1 + 0 as casted,
col1 REGEXP '^[+-]?[0-9]*([0-9]\\.|[0-9]|\\.[0-9])[0-9]*(e[+-]?[0-9]+)?$' as isNumeric
from myTable;
结果:
col1 | casted | isNumeric
-------|---------|----------
00.00 | 0 | 1
+1 | 1 | 1
.123 | 0.123 | 1
-.23e4 | -2300 | 1
12.e-5 | 0.00012 | 1
3.5e+6 | 3500000 | 1
a | 0 | 0
e6 | 0 | 0
+e0 | 0 | 0
Demo