如何在mysql中获取左子串

时间:2014-09-05 17:46:56

标签: mysql substring string-matching

它有点奇怪,但我找不到一种快速简单的方法来解决我的任务:

我有许多行具有不同的绝对路径,如:

  • /application/themes/openbank/images/prettyPhoto/light_square/default_thumbnail.gif
  • /application/themes/openbank/images/default_thumbnail.png
  • /application/themes/openbank/images/prettyPhoto/light_square/a_s.pdf

我希望将它们拆分为

  • parent_path(“例如/ application / themes / openbank / images / prettyPhoto / light_square /”)
  • file_name(“例如default_thumbnail.gif”)

注意:文件名的长度和分隔符的数量是可变的。

SUBSTRING_INDEX('/application/themes/openbank/images/prettyPhoto/light_square/default_thumbnail.gif', '/', -1)

我正确获取了file_name, 但我找不到一种方法来检索左边的部分。 我尝试了LEFT(),RIGHT()和all other mysql's string function但没有成功

Linuxatico

3 个答案:

答案 0 :(得分:3)

请尝试以下内容获取parent_path

select reverse(substring(reverse('/application/themes/openbank/images/prettyPhoto/light_square/default_thumbnail.gif'),instr(reverse('/application/themes/openbank/images/prettyPhoto/light_square/default_thumbnail.gif'),'/')))

答案 1 :(得分:2)

select substr( path, 1, instr(path, substring_index( path, '/', -1)) - 1 ) as "PARENT_PATH", substring_index(path, '/', -1 ) as "FILE_NAME" from table1;

答案 2 :(得分:1)

另一种方法是LEFT,SUBSTRING_INDEX和CHAR_LENGTH的组合: 我的解决方案采用字符串的左侧部分,长度=长度(绝对路径) - 长度(文件部分)。

SET @content = '/application/themes/openbank/images/prettyPhoto/light_square/default_thumbnail.gif';
SELECT 
    LEFT(
       @content, 
       CHAR_LENGTH(@content) - CHAR_LENGTH(SUBSTRING_INDEX(@content, '/', -1))
    );

查看this fiddle中的三个第一个答案。

我确定还有其他方法可以获得理想的结果。