MySQL 如何在MySQL中检查一个值是否为整数?

MySQL 如何在MySQL中检查一个值是否为整数?

检查给定的值是否为字符串,我们使用cast()函数。如果值不是数字,则返回0,否则将返回数字值。通过这种方法,我们可以检查值是否为整数。

阅读更多:MySQL 教程

情况1-检查带有整数的字符串

mysql> select cast('John123456' AS UNSIGNED);

以下是输出结果。它显示值不是数字,因此返回0。

+--------------------------------+
| cast('John123456' AS UNSIGNED) |
+--------------------------------+
|                               0|
+--------------------------------+
1 row in set, 1 warning (0.00 sec)

情况2-仅检查整数值

mysql> select cast('123456' AS UNSIGNED);

以下是输出结果。它显示值为数字,因此返回值本身。

+----------------------------+
| cast('123456' AS UNSIGNED) |
+----------------------------+
|                      123456|
+----------------------------+
1 row in set (0.00 sec)

此逻辑也适用于浮点数。

以下是带浮点数值的查询。

mysql>  SELECT CAST('78.90' AS UNSIGNED);

以下是输出结果。

+---------------------------+
| CAST('78.90' AS UNSIGNED) |
+---------------------------+
|                         78|
+---------------------------+
1 row in set, 1 warning (0.00 sec)

使用常规运算符的备用逻辑

它适用于任何值的所有条件,甚至是浮点数。

让我们创建一个新表。

mysql> create table CheckingIntegerDemo
   -> (
   -> Value varchar(200)
   -> );
Query OK, 0 rows affected (0.88 sec)

向表中插入记录。

mysql> insert into CheckingIntegerDemo values('John123456');
Query OK, 1 row affected (0.10 sec)

mysql>  insert into CheckingIntegerDemo values('123456');
Query OK, 1 row affected (0.16 sec)

mysql> insert into CheckingIntegerDemo values('123.456');
Query OK, 1 row affected (0.16 sec)

显示所有记录。

mysql> select *from CheckingIntegerDemo;

以下是输出结果。

+------------+
| Value      |
+------------+
| John123456 |
| 123456     |
| 123.456    |
+------------+
3 rows in set (0.00 sec)

在上面的输出中,只有123456是整数,其余的不是。

检查值是否为整数的语法。

select yourColumnName from yourTableName where yourColumnName REGEXP '^-?[0-9]+$';

我们使用正则表达式的查询。这将仅输出整数值。

mysql> select Value from CheckingIntegerDemo where Value REGEXP '^-?[0-9]+$';

以下是输出结果。

+--------+
| Value  |
+--------+
| 123456 |
+--------+
1 row in set (0.00 sec)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程