如何检查 MySQL 中的列值是字符串还是数字?

mysqlmysqli database

如果您只想要字符串值,请使用以下语法 −

select *from yourTableName where yourColumnName NOT regexp '^[0-9]+$';

如果您只想要数字,请使用以下语法 −

select *from yourTableName where yourColumnName regexp '^[0-9]+$';

首先我们创建一个表 −

mysql> create table DemoTable(
   Id varchar(100)
);
Query OK, 0 rows affected (0.49 sec)

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable values('1000');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('Carol_Smith');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('2000');
Query OK, 1 row affected (0.10 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable;

这将产生以下输出 −

+-------------+
| Id          |
+-------------+
| 1000        |
| John        |
| Carol_Smith |
| 2000        |
+-------------+
4 rows in set (0.00 sec)

案例 1 − 以下是仅获取字符串值 − 的查询

mysql> select *from DemoTable where Id NOT regexp '^[0-9]+$';

这将产生以下输出,仅显示字符串列值 −

+-------------+
| Id          |
+-------------+
| John        |
| Carol_Smith |
+-------------+
2 rows in set (0.00 sec)

案例 2 − 以下是仅获取数字 − 的查询

mysql> select *from DemoTable where Id regexp '^[0-9]+$';

这将产生以下输出,仅显示数字列值 −

+------+
| Id   |
+------+
| 1000 |
| 2000 |
+------+
2 rows in set (0.00 sec)

相关文章