sql進階 – 欄位也能實現split拆分?

  • 2019 年 12 月 26 日
  • 筆記

今天學習一個sql函數

SUBSTRING_INDEX(str,delim,count)

  • 函數返回分隔符出現指定次數之前的字元串。如果 count 為正數,則返回最後一個分隔符出現位置左側的所有字元;如果count為負數,則返回最後一個分隔符出現位置右側的所有字元。
  • 該函數區分大小寫

應用示例:

mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', 2);          -> 'www.mysql'  mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', -2);          -> 'mysql.com'  

使用得當可以實現split拆分欄位功能。 假設有表內容如下:

mysql> select * from a;  +--------------------------+  | login_info               |  +--------------------------+  | 10.23.1.8&root&pwd123456 |  +--------------------------+  1 row in set (0.00 sec)  

該欄位由3部分組成,分別對應ip, user, password,現在要使用sql將該欄位拆分,程式碼如下:

mysql> select      -> `login_info`,      -> substring_index(`login_info`, "&", 1) as `ip`,      -> substring_index(substring_index(`login_info`,"&",-2),"&",1) as `user`,      -> substring_index(`login_info`,"&",-1) as `password`      -> from a;  +--------------------------+-----------+------+-----------+  | login_info               | ip        | user | password  |  +--------------------------+-----------+------+-----------+  | 10.23.1.8&root&pwd123456 | 10.23.1.8 | root | pwd123456 |  +--------------------------+-----------+------+-----------+  1 row in set (0.00 sec)  

是不是有點意思?