substring_index

Name

SinceVersion 1.2

SUBSTRING_INDEX

description

Syntax

VARCHAR substring_index(VARCHAR content, VARCHAR delimiter, INT field)

返回 content 的子字符串,在 delimiter 出现 field 次的位置按如下规则截取: 如果 field > 0,则从左边算起,返回截取位置前的子串; 如果 field < 0,则从右边算起,返回截取位置后的子串; 如果 field = 0,返回一个空串(content 不为null), 或者Null (content = null)。

  • delimiter 大小写敏感,且是多字节安全的。
  • delimiter 和 field 参数需要是常量, 不支持变量。

example

1. mysql> select substring_index("hello world", " ", 1);
2. +----------------------------------------+
3. | substring_index("hello world", " ", 1) |
4. +----------------------------------------+
5. | hello                                  |
6. +----------------------------------------+
7. mysql> select substring_index("hello world", " ", 2);
8. +----------------------------------------+
9. | substring_index("hello world", " ", 2) |
10. +----------------------------------------+
11. | hello world                            |
12. +----------------------------------------+
13. mysql> select substring_index("hello world", " ", -1);
14. +-----------------------------------------+
15. | substring_index("hello world", " ", -1) |
16. +-----------------------------------------+
17. | world                                   |
18. +-----------------------------------------+
19. mysql> select substring_index("hello world", " ", -2);
20. +-----------------------------------------+
21. | substring_index("hello world", " ", -2) |
22. +-----------------------------------------+
23. | hello world                             |
24. +-----------------------------------------+
25. mysql> select substring_index("hello world", " ", -3);
26. +-----------------------------------------+
27. | substring_index("hello world", " ", -3) |
28. +-----------------------------------------+
29. | hello world                             |
30. +-----------------------------------------+
31. mysql> select substring_index("hello world", " ", 0);
32. +----------------------------------------+
33. | substring_index("hello world", " ", 0) |
34. +----------------------------------------+
35. |                                        |
36. +----------------------------------------+

keywords

1. SUBSTRING_INDEX, SUBSTRING