SUBSTRING_INDEX()
函数说明
此函数 SUBSTRING_INDEX() 以分隔符为索引,获取不同索引位的字符。
如果 count 为正,则返回最后一个分隔符左侧(从左侧开始计数)的所有内容。
如果 count 为负数,则返回最后一个分隔符右侧(从右侧开始计数)的所有内容。
如果参数为 NULL,SUBSTRING_INDEX() 将返回 NULL。
语法说明
1. > SUBSTRING_INDEX(str,delim,count)
即,substring_index(“待截取有用部分的字符串”,“截取数据依据的字符”,截取字符的位置 N)
参数释义
| 参数 | 说明 |
|---|---|
| str | 字符串 |
| delim | 分隔符 |
| count | 表示 delim 出现次数的整数。 |
示例
1. mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', 2);
2. +--------------------------------------+
3. | substring_index(www.mysql.com, ., 2) |
4. +--------------------------------------+
5. | www.mysql |
6. +--------------------------------------+
7. 1 row in set (0.03 sec)
9. mysql> select substring_index('xyz', 'abc', 9223372036854775808);
10. +------------------------------------------------+
11. | substring_index(xyz, abc, 9223372036854775808) |
12. +------------------------------------------------+
13. | xyz |
14. +------------------------------------------------+
15. 1 row in set (0.02 sec)
17. mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', -2);
18. +---------------------------------------+
19. | substring_index(www.mysql.com, ., -2) |
20. +---------------------------------------+
21. | mysql.com |
22. +---------------------------------------+
23. 1 row in set (0.02 sec)
25. mysql> SELECT SUBSTRING_INDEX(SUBSTRING_INDEX('192,168,8,203', ',', 2), ',',-1);
26. +--------------------------------------------------------------+
27. | substring_index(substring_index(192,168,8,203, ,, 2), ,, -1) |
28. +--------------------------------------------------------------+
29. | 168 |
30. +--------------------------------------------------------------+
31. 1 row in set (0.02 sec)
33. create table test(a varchar(100), b varchar(20), c int);
34. insert into test values('www.mysql.com', '.', 0);
35. insert into test values('www.mysql.com', '.', 1);
36. insert into test values('www.mysql.com', '.', 2);
37. insert into test values('www.mysql.com', '.', 3);
38. insert into test values('www.mysql.com', '.', 9223372036854775808);
39. insert into test values('www.mysql.com', '.', -1);
40. insert into test values('www.mysql.com', '.', -2);
41. insert into test values('www.mysql.com', '.', -3);
42. mysql> select SUBSTRING_INDEX(a, b, c) from test;
43. +--------------------------+
44. | substring_index(a, b, c) |
45. +--------------------------+
46. | |
47. | www |
48. | www.mysql |
49. | www.mysql.com |
50. | com |
51. | mysql.com |
52. | www.mysql.com |
53. +--------------------------+
54. 7 rows in set (0.02 sec)
