MySQL查詢以透過字串欄位中的數字字元對行進行分組?
要執行此操作,可以使用 + 運算子將 0 與字串欄位連線起來。這裡的場景是我們需要從一個字串欄位“9844Bob”獲取數字“9844”。
我們首先建立一個表——
mysql> create table DemoTable ( StudentId varchar(100) ); Query OK, 0 rows affected (0.92 sec)
使用 insert 命令向表中插入一些記錄——
mysql> insert into DemoTable values('9844Bob'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values('6375DavidMiller'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values('007'); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable values('97474BobBrown'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values('9844Bob56Taylor'); Query OK, 1 row affected (0.16 sec)
使用 select語句從表中顯示所有記錄——
mysql> select *from DemoTable;
這將生成以下輸出——
+-----------------+ | StudentId | +-----------------+ | 9844Bob | | 6375DavidMiller | | 007 | | 97474BobBrown | | 9844Bob56Taylor | +-----------------+ 5 rows in set (0.00 sec)
以下是透過字串欄位中的數字字元對行進行分組的查詢——
mysql> select StudentId,0+StudentId as GroupValue from DemoTable;
這將生成以下輸出——
+-----------------+------------+ | StudentId | GroupValue | +-----------------+------------+ | 9844Bob | 9844 | | 6375DavidMiller | 6375 | | 007 | 7 | | 97474BobBrown | 97474 | | 9844Bob56Taylor | 9844 | +-----------------+------------+ 5 rows in set, 4 warnings (0.00 sec)
廣告