2014-09-05 41 views
2

它SEMS奇怪,但我无法找到一个快速和简单的方法来解决我的任务:如何获得左子在MySQL

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

  • /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(“如/应用/主题/ openbank /图像/ prettyPhoto/light_square/“)
  • FILE_NAME(” 如default_thumbnail.gif“)

注意:文件名的lenght和隔板的数量是可变的

带。

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

我正确地得到FILE_NAME, 但我不能找到一种方法来检索左侧部分。 我试过LEFT(),RIGHT(),并all other mysql's string function没有成功

Linuxatico

+0

所有这些都是好的和完整的答案(VMai,Brian Ridgeway和Ronak Shah's),都值得一个“接受的答案标记”。我认为最完整和最干净的是,@VMai之一,在瘾,小提琴是非常自动说明。谢谢大家。 – linuxatico 2014-09-08 07:31:15

回答

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工作的三个第一选择。

我敢肯定,还有其他一些方法来获得所需的结果。

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'),'/'))) 
+0

+1你比我快5秒! :) – 2014-09-05 18:05:54

+0

@Bill Karwin .. :) – 2014-09-05 18:06:27

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

+1,包括你的解决方案在我的小提琴。我希望你不介意。 – VMai 2014-09-05 18:35:39