mysql - 如何使用MySQL字符串操作?

标签 mysql sql substring

我想知道如何在我的数据库上使用 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 before count occurrences of the delimiter delim. If count is positive, everything to the left of the final delimiter (counting from the left) is returned. If count 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/

相关文章:

sql - 无法进行 mysql 查询

mysql - SQL查询根据条件选择记录?

mysql - SQL:将员工分组在一行中

java - 大字符串中最长的重复且不重叠的子字符串

java - 删除 Java 字符串中的最后 n 行(句子)

php - Datatables 中的 WordPress 用户,具有排序、搜索和分页功能

mysql - 使用 MySQL 获取时间戳

mysql - 如何简化这条 SQL 语句?

php - MySQL 与 AS 结合 HAVING 的困难

c++ - 从 C++ 中的字符串中获取每个单独的单词