mysql中怎麼樣過濾字符串中的數字

       今天,有網友郵件問我,怎麼樣過濾掉字符串中的數字,好比: mysql> select * from TEST; +---------+------------------------+ | Contact | Address                | +---------+------------------------+ | A       | 3995 Thomas Drive      | | B       | 95 Dewberry Ct         | | C       | 635 mill st            | | D       | 3050 E 6TH ST          | | E       | 3216 Lawndale Ave      | | F       | 207 240th st.          | | G       | 19 Lockhouse Rd. #14-3 | +---------+------------------------+ 但願能將address中的數字所有過濾掉,變成以下格式: +---------+---------------------+ | contact | FILTER_NUM(ADDRESS) | +---------+---------------------+ | A       |  Thomas Drive       | | B       |  Dewberry Ct        | | C       |  mill st            | | D       |  E TH ST            | | E       |  Lawndale Ave       | | F       |  th st.             | | G       |  Lockhouse Rd. #-   | +---------+---------------------+ 立刻想到使用mysql中字符串的replace功能來實現,可是查幫助後發現,replace只能對某個字符串進行替換,而沒法對多個字符串替換,因而想到了一個笨辦法,循環使用replace,以下: mysql> select ADDRESS,REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(ADDRESS,'0',''),'1',''),'2',''),'3',''),'4',''),'5',''),'6',''),'7',''),'8',''),'9','') filter_num from TEST; +------------------------+-------------------+ | ADDRESS                | filter_num        | +------------------------+-------------------+ | 3995 Thomas Drive      |  Thomas Drive     | | 95 Dewberry Ct         |  Dewberry Ct      | | 635 mill st            |  mill st          | | 3050 E 6TH ST          |  E TH ST          | | 3216 Lawndale Ave      |  Lawndale Ave     | | 207 240th st.          |  th st.           | | 19 Lockhouse Rd. #14-3 |  Lockhouse Rd. #- | +------------------------+-------------------+ 7 rows in set (0.00 sec) 固然,也能夠寫一個函數,之後遇到相似問題也能夠使用: mysql> delimiter // mysql>  create function filter_num(str varchar(100)) returns varchar(100)     -> reads sql data     -> return REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(str,'0',''),'1',''),'2',''),'3',''),'4',''),'5',''),'6',''),'7',''),'8',''),'9','');     -> // Query OK, 0 rows affected (0.00 sec) mysql> select *,FILTER_NUM(ADDRESS) from TEST; +---------+------------------------+---------------------+ | Contact | Address                | FILTER_NUM(ADDRESS) | +---------+------------------------+---------------------+ | A       | 3995 Thomas Drive      |  Thomas Drive       | | B       | 95 Dewberry Ct         |  Dewberry Ct        | | C       | 635 mill st            |  mill st            | | D       | 3050 E 6TH ST          |  E TH ST            | | E       | 3216 Lawndale Ave      |  Lawndale Ave       | | F       | 207 240th st.          |  th st.             | | G       | 19 Lockhouse Rd. #14-3 |  Lockhouse Rd. #-   | +---------+------------------------+---------------------+ 7 rows in set (0.00 sec) 不過,這種方法效率不高,由於要對文本進行10次替換,若是文本很大,效率將很是低下,若是要更加高效,能夠寫更復雜的函數,來進行一次掃描,就完成所有字符串的替換。
相關文章
相關標籤/搜索