如何检查MySQL中的值是否为整数?

时间:2020-03-05 18:56:51  来源:igfitidea点击:

我看到在MySQL中有Cast()Convert()函数从值创建整数,但是有什么方法可以检查值是否是整数?我正在寻找PHP中的is_int()之类的东西。

解决方案

回答

将其与正则表达式匹配。

c.f. http://forums.mysql.com/read.php?60,1907,38488#msg-38488引用如下:

Re: IsNumeric() clause in MySQL??
  
Posted by: kevinclark ()
  
Date: August 08, 2005 01:01PM
  
  
I agree. Here is a function I created for MySQL 5:
CREATE FUNCTION IsNumeric (sIn varchar(1024)) RETURNS tinyint
RETURN sIn REGEXP '^(-|\+){0,1}([0-9]+\.[0-9]*|[0-9]*\.[0-9]+|[0-9]+)$';
This allows for an optional plus/minus sign at the beginning, one optional decimal point, and the rest numeric digits.

回答

我假设我们要检查一个字符串值。一种不错的方法是REGEXP运算符,将字符串与正则表达式匹配。简单地做

select field from table where field REGEXP '^-?[0-9]+$';

这相当快。如果字段是数字,则只需测试

ceil(field) = field

反而。