SQL query how to update all duplicate filenames?

对着背影说爱祢 提交于 2020-07-30 04:25:13

问题


I wanted to check data from documents table where there are duplicate filename or the same filename with the same employeeId and then update those filenames so that there will be no duplicates.

For example employeeId 216 has 2 or more documents with the same filenames which is DOC-15.. and DOC-15 , I wanted to rename the other file or add prefix to make it unique so that there will be no duplicates.

#Code

const documents = await sequelizeClient.query(
        `SELECT id, filename, COUNT(filename) FROM documents GROUP BY filename
      HAVING COUNT(filename) > 1;`,
        { type: QueryTypes.SELECT },
      );

      const promises = [];
      // eslint-disable-next-line no-plusplus
      for (let i = 0; i < documents.length; i++) {
        const prefix = Date.now().toString();
        const fileParts = documents[i].filename.split('.');
        const finalname = `${fileParts[0]}-${prefix}.${fileParts[1]}`;
        // eslint-disable-next-line no-await-in-loop
        promises.push(queryInterface.sequelize.query(`UPDATE ${EmployeeDocumentsModel.tableName} SET filename='${finalname}' WHERE employeeID=${documents[i].id};`));
      }
      await Promise.all(promises);

#Query on getting data with duplicate filenames

 SELECT id, filename, employeeId, COUNT(filename) FROM documents GROUP BY filename
      HAVING COUNT(filename) > 1;

#Data

来源:https://stackoverflow.com/questions/63068502/sql-query-how-to-update-all-duplicate-filenames

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!