如何在 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)
);
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)

CASE 1 − 以下是僅獲取字串值的查詢 −

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

這將生成以下僅顯示字串列值的輸出 −

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

CASE 2 − 以下是僅獲取數字的查詢 −

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

這將生成以下僅顯示數字列值的輸出 −

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

更新於:04-10-2019

904 個瀏覽量

開啟你的 事業

完成課程獲得認證

開始
廣告