从数据库中存储的完整路径中提取目录名

Extract dirname from full path stored in database

如何从存储在数据库中的完整路径中仅提取目录名。

我需要将扫描文件插入另一个 table,它将仅按目录名过滤。

ex.

  1. /mnt/HD/HD_a2/Watch Me.mp3
  2. /mnt/HD/HD_a2/mymusic/sample.mp3
    • full path stored in tbl_files

INSERT INTO tbl_transcode (file_id) Select file_id from tbl_files where UPPER(file_path) Like CONCAT((Select source_path from tbl_transcode_folder where trancode_folder_id = 1 ),'%') and media_type = 'video'

但是我只需要dirname插入tbl_transcode,我觉得LIKE不好用

例如。我只想搜索此 /mnt/HD/HD_a2/Watch Me.mp3 的目录名,但当我使用 /mnt/HD/HD_a2% 时,它 return 我喜欢这样。还显示了其他目录名。

  1. /mnt/HD/HD_a2/Watch Me.mp3
  2. /mnt/HD/HD_a2/mymusic/sample.mp3

如果我的理解是正确的,您收集的是每个文件的目录名称,而不是文件目录的完整路径。

以下答案特定于 Oracle,其中我们使用了 regexp_substr 方法。

To get the full path with directory name we can use the following regular expression:

substr(REGEXP_SUBSTR(c1,'^(.*/)*'),0,instr(REGEXP_SUBSTR(c1,'^(.*/)*'),'/',-1)-1)

To get only the directory name we can use the following regular expression:

replace(regexp_substr(substr(REGEXP_SUBSTR(c1,'^(.*/)*'),0,instr(REGEXP_SUBSTR(c1,'^(.*/)*'),'/',-1)-1),'/[a-zA-Z_0-9]+$'),'/','')

这里 c1 是我最后使用的示例列。

因此,您更新后的查询将如下所示:

INSERT INTO tbl_transcode (file_id) 
Select file_id from tbl_files where UPPER(file_path) = upper(substr(REGEXP_SUBSTR(source_path,'^(.*/)*'),0,instr(REGEXP_SUBSTR(source_path,'^(.*/)*'),'/',-1)-1)) and media_type = 'video';

你也可以勾选thissqlfiddle

更新(针对 MySQL 的回答):

我们可以利用MySQL中的substring_indexlocatesubstring方法来实现目录名的提取。

substring_index方法returns子串中某个字符出现的次数。这里感兴趣的字符是 /。因此,从给定的目录路径调用 substring_index(c1,'/',-1) returns 文件名。

接下来我们可以使用locate找到文件名位置的索引,并使用substr.

得到文件名开头的子字符串

To get the file names:

SELECT substring_index(c1,'/',-1) FROM t1;

To get the directory name with full path:

SELECT substring(c1,1,locate(substring_index(c1,'/',-1),c1)-1) FROM t1;

To get only the directory name:

SELECT substring_index(substring(c1,1,locate(substring_index(c1,'/',-1),c1)-2),'/',-1) FROM t1;

因此,在您的案例的更新查询中将如下所示:

INSERT INTO tbl_transcode (file_id) Select file_id from tbl_files where UPPER(file_path) = upper(substring_index(substring(source_path,1,locate(substring_index(source_path,'/',-1),source_path)-2),'/',-1)) and media_type = 'video';

检查 this fiddle 的工作示例