如何在MySQL中检查列值是否包含字符串或数字?
如果只需要字符串值,请使用以下语法-
select *from yourTableName where yourColumnName NOT regexp '^[0-9]+$';
如果只想要数字,则使用以下语法-
select *from yourTableName where yourColumnName regexp '^[0-9]+$';
让我们首先创建一个表-
mysql> create table DemoTable( Id varchar(100) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values('1000'); mysql> insert into DemoTable values('John'); mysql> insert into DemoTable values('Carol_Smith'); mysql> insert into DemoTable values('2000');
使用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)