如何通过sql查询获取文件的文件扩展名?

时间:2012-06-08 08:40:07

标签: mysql sql subquery dao

我有一个名为datas的表,我正在执行这样的查询:

SELECT linkurl AS DOWNLOADURL,
       lastrevlevel AS VERSION,
       code AS DESCRIPTION,
       created AS RELEASEDATE,
       name AS TYPE
FROM datas
WHERE id IN (SELECT child_id
          FROM   datas _datas
          WHERE  parent_id = (SELECT Max(id)
                              FROM   datas
                              WHERE  code = 'AN4307SW'))

它会返回如下结果:

DOWNLOADURL               VERSION DESCRIPTION RELEASEDATE    TYPE
/artifacts/download.txt   2.0     images       25/6/12      download.txt

Type列中,我正在查找该文件的名称。我需要在Type列中获取文件名的文件扩展名。我怎样才能做到这一点?

示例:

TYPE
.txt
.pdf
.xls

6 个答案:

答案 0 :(得分:21)

您可以使用SUBSTRING_INDEX。像这样:

select linkurl as DOWNLOADURL,lastrevlevel as VERSION,
code  as DESCRIPTION,created as RELEASEDATE,
SUBSTRING_INDEX(name,'.',-1) as TYPE
from datas where id in
(select child_id from datas _datas 
where parent_id=( select max(id) from datas 
where code = 'AN4307SW'))

修改

如果您看到有关此功能的文档,我认为这将很好地适用于您的要求。

  

在计数出现之前,从字符串str返回子字符串   分隔符delim。如果计数是正数,那么一切都在左边   返回最终分隔符(从左边开始计数)。如果算数是   否定,最终分隔符右侧的所有内容(计数   从右边)返回。 SUBSTRING_INDEX()执行一个   搜索delim时区分大小写匹配。

这也将处理这样的情况:

select SUBSTRING_INDEX('Test.Document.doc','.',-1);

<强> EDIT2

如果你正在使用oracle。请在下次正确的问题上标记问题。 oracle中没有SUBSTRING_INDEX。但我能看到你可以很容易地做到这一点:

SELECT SUBSTR('Test.Document.doc', INSTR('Test.Document.doc', '.',-1)) 
FROM dual; 

像这样的完整查询:

select linkurl as DOWNLOADURL,lastrevlevel as VERSION,
    code  as DESCRIPTION,created as RELEASEDATE,
    SUBSTR(name, INSTR(name, '.',-1))  as TYPE
    from datas where id in
    (select child_id from datas _datas 
    where parent_id=( select max(id) from datas 
    where code = 'AN4307SW'))

参考here

答案 1 :(得分:2)

select linkurl as DOWNLOADURL,lastrevlevel as VERSION,
code  as DESCRIPTION,created as RELEASEDATE,reverse(substring(reverse(name), 1,charindex('.', reverse(name))-1)) as TYPE
from datas where id in
(select child_id from datas _datas 
where parent_id=( select max(id) from datas 
where code = 'AN4307SW'))  

答案 2 :(得分:1)

认为你需要这样的东西

SELECT REPLACE(name,SUBSTRING(name ,0, CHARINDEX('.', name )),'')

答案 3 :(得分:0)

SELECT
    SUBSTRING(file_name,(LENGTH(file_name)-LOCATE('.',REVERSE(file_name)))+2)
FROM <table name> WHERE file_id=<file_id>;

答案 4 :(得分:0)

SELECT REVERSE(SUBSTRING(REVERSE(name),1,LOCATE('.',REVERSE(name),1‌​)));

答案 5 :(得分:0)

可以这样做

SELECT SUBSTRING_INDEX(FILE_NAME,"." ,-1) from TABLE_NAME