我想知道如何在我的数据库上使用 MySQL 字符串函数。
我有 MySQL 数据库,其中包含以下类似数据
+---+-----------------------+
|id | name |
+---+-----------------------+
| 1 | /sun/steave/xyz |
| 2 | /mon/alan/asdsas |
| 3 | /sun/mark/we |
| 4 | /wed/john/rtd |
| 5 | /thu/mich/dfgsd |
+---+------------------- -+
其中名称为 type varchar(255)
.
我只想选择名称,即 (/sun/steave/xyz)。
我尝试过
select substr(name,4) from my_table;
(我不能在 substring
中使用长度,例如 (name,4,6)
因为名称是动态的)
它返回我
steave/xyz
alan/asdsas
mark/we
john/rtd
mich/dfgsd
如何从表格中仅选择姓名? 这可以通过 MySQL 字符串函数实现吗?
最佳答案
您可以使用几个 substring_index
调用以在 /
之间剪切字符串:
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(name, '/', 3), '/', -1)
FROM my_table
编辑:
根据评论中的要求,提供更多详细信息。引用 substring_index
上的文档:
SUBSTRING_INDEX(str,delim,count) Returns the substring from string
str
beforecount
occurrences of the delimiterdelim
. Ifcount
is positive, everything to the left of the final delimiter (counting from the left) is returned. Ifcount
is negative, everything to the right of the final delimiter (counting from the right) is returned.
我们以字符串'/sun/steave/xyz'
为例。内部 substring_idex
调用返回第三个 /
之前的子字符串,因此对于我们的情况,它返回 '/sun/steave'
。外部 substring_index
返回最后一个 '/'
之后的子字符串,因此给定 '/sun/steave'
它将仅返回 '牛排'
。
关于mysql - 如何使用MySQL字符串操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26337411/