如何在MySQL中檢查值是否為整數?
要檢查給定值是否為字串,我們使用cast()函式。如果值不是數值,則返回0,否則返回數值。透過這種方式,我們可以檢查值是否為整數。
案例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)
廣告