如何在 MySQL 中使用比較運算子處理數字字串?


若要對數字字串使用比較運算子,可以使用 substring() 方法。我們首先建立一個表 -

mysql> create table DemoTable1881
   (
   UserId int,
   UserEducationGap varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)

使用 insert 命令向表內插入一些記錄 -

mysql> insert into DemoTable1881 values(101,'5-9');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1881 values(102,'2-4');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1881 values(103,'4-8');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1881 values(104,'7-12');
Query OK, 1 row affected (0.00 sec)

使用 select 語句在表中顯示所有記錄 -

mysql> select * from DemoTable1881;

這將產生以下輸出 -

+--------+------------------+
| UserId | UserEducationGap |
+--------+------------------+
|    101 | 5-9              |
|    102 | 2-4              |
|    103 | 4-8              |
|    104 | 7-12             |
+--------+------------------+
4 rows in set (0.00 sec)

以下查詢可在 MySQL 中將比較運算子用於數字字串 

mysql> select * from DemoTable1881 where
cast(substring(UserEducationGap, 1, instr(UserEducationGap, '-')-1) as signed) >= 4;

這將產生以下輸出 -

+--------+------------------+
| UserId | UserEducationGap |
+--------+------------------+
|    101 | 5-9              |
|    103 | 4-8              |
|    104 | 7-12             |
+--------+------------------+
3 rows in set (0.00 sec)

更新於:2020 年 2 月 25 日

79 人次瀏覽

開啟你的 職業

透過完成課程獲得認證

開始
廣告