如果名称存在mysql,则增加名称

时间:2018-04-03 16:56:25

标签: mysql

我的结构文件表为

CREATE TABLE document_history 
(
 id int auto_increment primary key, 
 document_id int,
 name varchar(100),
 modified datetime,
 user_id int 
 );

及以下值

ID   |  DOCUMENT_ID  |  NAME              |  MODIFIED     |   USER_ID
33   |  81           |  document.docx     |  2014-03-21   |   1
34   |  82           |  doc.docx          |  2014-03-21   |   1
35   |  82           |  doc(1).docx       |  2014-03-21   |   1
36   |  82           |  doc(2).docx       |  2014-03-21   |   1

因此,当用户上传名为doc.docx的文件时,应将其重命名为doc(3).docx,依此类推。

我正在尝试编写查询,这将为我的文件名提供下一个增量。尝试过regxps但仍无法通过查询实现。此外,我的表可以有数百万个必需但有一些过滤条件。

1 个答案:

答案 0 :(得分:0)

这将找到给定文档ID的文档名称,然后执行增量计数器以分配新文档名称(版本)。我按记录ID对结果进行排序,然后仅显示最新(和新)文档名称。

select t.new_name
from (
     select id, 
            concat(
                   case when locate('(',name)>0 
                        then left(name,locate('(',name)-1) 
                        else left(name,locate('.',name)-1) end,
                        '(',
                        @rownum := @rownum + 1,
                        ')',
                        right(name,locate('.',reverse(name)))) as new_name
              from document_history, 
                  (select  @rownum := 0) r
              where document_id=81
      ) t
order by t.id desc
limit 1;

Result:
for document_id=81:   document(1).docx
for document_id=82:   doc(3).docx
相关问题